public class CountWords { static int i = 0; static int c = 0; static int wordcount(String str) { char ch[] = new char[str.length()]; for (i = 0; i < str.length(); i++) { ch[i] = str.charAt(i); if (((i > 0) && (ch[i] != ' ') && (ch[i - 1] == ' ')) || ((ch[0] != ' ') && (i == 0))) { c++; } } return c; } public static void main(String args[]) { String str = " I do not like green eggs and ham "; int count = CountWords.wordcount(str); System.out.println("str: " + str); System.out.println("count : " + count); } }
$ java CountWords str: I do not like green eggs and ham count : 8
Java count number of words in a String. Count the exact number of words in a string that has empty spaces between words. Counting number of words in sentence. Count words in a given string