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.
I made a function:
public static int wordCount(String s){
int counter = 0;
for(int i=0; i<=s.length()-1; i++) {
if(Character.isLetter(s.charAt(i))){
counter++;
for(i<=s.length()-1; i++){
if(s.charAt(i)==' '){
counter++;
}
}
}
}
return counter;
}
But i know this has 1 limitation that it will also count the number of spaces after all the words in the string have finished nad it will also count 2 blank spaces as possibly being 2 words :( Is there a predefined function for word count? or can this code be corrected?
If you want to ignore leading, trailing and duplicate spaces you can use
String trimmed = text.trim();
int words = trimmed.isEmpty() ? 0 : trimmed.split("\\s+").length;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With