String is very popular among Interviewer, and you are bound to see some questions on any programming interview, Java Interviews are no exception. Questions based from Java fundamentals like why String is Immutable in Java to questions based on coding skills e.g. reverse String using recursion in Java, String has always troubled candidates. In this article, we will see a similar questions, how to count number of words in Java String. Before jumping to solution, just read below to make sure what a word means here. It's sequence of one or more non-space characters. We will see two examples to find number of words in Java String, first one is based upon pure logic, where it goes through all characters from String and then count each word. Second is more interesting than first one, here we have used regular expression to find all words. We split String by white space, passing \\s+ means greedy search i.e. it includes one or more white spaces. BTW, this is one of the question I forgot to share when I wrote about Top 20 String coding questions, will include it on that list for sure.
Write a function in Java which accept a String argument and returns number of words in it. A word is a sequence of one or more non-space character i.e. any character other than '' (empty String). This should be your method signature :
This method should return 5 if passed "Java is best programming language" and return 3 if passed "Java is great". Similarly a call to wordCount(" ") should return 0.
That's all about how to find number of words in a Java String. We have seen 2 examples to do that. It's pretty easy using split() method of String class, which also accepts regular expression. By using regex \\s+ we can split String into words. As I said, don't forget to write unit test on interviews, Interviewer always expect you to write production quality code and unit testing is part of that.
If you like this coding problem and hungry for more coding questions from Interviews, check out these amazing collection :
Problem :
![Java program to count number of words in String](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgH9En1hzFynvedU3LsRlVOLzDWC0JTMNPbG67U-80M4FvoCWPOmo4nmW0-kkGbD8hLuHhuJuBIQXEGn1twUHQubkJ9XBCXslB7LtaApRP8E3UDYpT_wxAxxkkYgupI1Zk1xignlBDMOTRq/s1600/17.jpg)
public int wordCount(String word);
This method should return 5 if passed "Java is best programming language" and return 3 if passed "Java is great". Similarly a call to wordCount(" ") should return 0.
Solution :
In order to implement this method we need to assume that two words are separated by space. We also need to ignore leading, trailing and multiple spaces between words. One way to solve this problem is to split String by space and then count number of parts. We will see two solution of this problem, here is the first one .How find number of words String - 2 Examples
In this sample program, we have two methods, first we will count number of words without using regular expression, and second will do the same but using regex./** * Java Program to count number of words in String * * @author Javin */ public class WordCounterProblem{ /* * This method return word count without using regular expression */ public int wordcount(String word) { if (word == null || word.isEmpty()) { return 0; } int count = 0; char ch[] = new char[word.length()]; for (int i = 0; i < word.length(); i++) { ch[i] = word.charAt(i); if (((i < 0) && (ch[i] != ' ') && (ch[i - 1] == ' ')) || ((ch[0] != ' ') && (i == 0))) { count++; } } return count; } /* * Counting number of words using regular expression. */ public int countWord(String word) { if (word == null) { return 0; } String input = word.trim(); int count = input.isEmpty() ? 0 : input.split("\\s+").length; return count; } }
Junit Test Case
Whenever you are asked to write code on Interview, make sure you write some unit test as well. Some time Interviewer will ask you explicitly, but many times they just want to see whether candidate follows development practice like unit testing and code review. For this problem, I have wrote five test, though in one method for the sake of brevity. First is a normal space separated word, second is empty String, third is String with just space and fourth is word separated with multiple white space. You can further add unit test for null String, String without white space, String with leading and trailing white space. I leave that to you.import static org.junit.Assert.*; import org.junit.Test; public class WordCounterTest { @Test public void wordCount() { Testing test = new Testing(); assertEquals(3, test.wordcount("JUnit is Best")); // string with three words assertEquals(0, test.wordcount("")); // empty string assertEquals(0, test.wordcount(" ")); // no words, just spaces assertEquals(3, test.wordcount("String is Immutable")); // words with multiple space in between assertEquals(2, test.wordcount("See you ")); // words with trailing space assertEquals(2, test.wordcount(" Good Morning")); // words with leading space assertEquals(0, test.wordcount(null)); // null check } @Test public void countWord() { Testing test = new Testing(); assertEquals(3, test.countWord("JUnit is Best")); assertEquals(0, test.countWord("")); assertEquals(0, test.countWord(" ")); assertEquals(3, test.countWord("String is Immutable")); assertEquals(2, test.countWord("See you ")); assertEquals(2, test.countWord(" Good Morning")); assertEquals(0, test.countWord(null)); } }
That's all about how to find number of words in a Java String. We have seen 2 examples to do that. It's pretty easy using split() method of String class, which also accepts regular expression. By using regex \\s+ we can split String into words. As I said, don't forget to write unit test on interviews, Interviewer always expect you to write production quality code and unit testing is part of that.
If you like this coding problem and hungry for more coding questions from Interviews, check out these amazing collection :
- 30 Programming questions from Job Interviews (list)
- 15 Data Structure and Algorithm Questions for Programmers (list)
- Write a Program to solve Producer Consumer Problem in Java. (Solution)
- How to reverse String in Java without using API methods? (Solution)
- Write a Program to check if a number is binary in Java? (Solution)
- How to find first non repeated characters from String in Java? (Solution)
- How to remove duplicates from array without using Collection API? (Solution)
- Write a Program to Check if a number is Power of Two or not? (Answer)
- How to Swap Two Numbers without using Temp Variable in Java? (Solution)
- How to check if LinkedList contains loop in Java? (Solution)
- How to find middle element of LinkedList in one pass? (Solution)
- How to find prime factors of a number in Java? (Solution)
- Write a Program to prevent Deadlock in Java? (Solution)
- How to check if a number is Palindrome or not? (Solution)
- How to remove duplicates from ArrayList in Java? (Solution)
- Write a Java Program to See if two String are Anagram of each other? (Solution)
- How to count occurrences of a character in String? (Solution)
- Write a Program to calculate Sum of Digits of a number in Java? (Solution)
- How to check if a number is Prime or not? (Solution)
- Write a Program to find Fibonacci Series of a Given Number? (Solution)
- How to check if a number is Armstrong number or not? (Solution)
- Write a Program to calculate factorial using recursion in Java? (Solution)
- How to check if Array contains duplicate number or not? (Solution)
No comments:
Post a Comment