Write a method called wordCount that accepts a String as its parameter and returns the number of words in the String. A word is a sequence of one or more nonspace characters (any character other than ' '). For example, the call wordCount("hello") should return 1, the call wordCount("how are you?") should return 3, the call wordCount(" this string has wide spaces ") should return 5, and the call wordCount(" ") should return 0.
public class CountWords {
public static int wordCount(String string) {
int count = 0;
// \\s+ regex, split the words based on white spaces
// split method takes the regex as an argument
String[] var = string.split("\\s+");
// if it is greater than zero count that as word
for (String str : var) {
if (str.length() > 0)
count++;
}
return count;
}
public static void main(String args[]) {
String string = "blackholes are always fascinates me;; ";
int numOfWords = CountWords.wordCount(string);
System.out.println(string+"contains " +numOfWords+ " words");
}
}
Output:
blackholes are always fascinates me;; contains 5 words