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
Simply use s.split(" ").length
and for wide spaces...use s.trim().replaceAll("\\s+"," ").split(" ").length
It should be easy with:
String[] arr = "how are you sir".split("\\s");
System.out.printf("Count [%d]%n", arr.length);
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;
public static int wordCount(String s){
if (s == null)
return 0;
return s.trim().split("\\s+").length;
}
Have fun with the function.
Added some lines to your code:
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++;
i++;
while (s.charAt(i)==' ')
i++;
}
}
}
}
return counter;
}
String str="I am a good boy";
String[] words=str.split("\\s+");
System.out.println(words.length);