javacodex.com
Java Examples
Java Examples
memu home questions

How to count number of words in a String?

Here is an example on how to count number of words in a String.

CountWords.java

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);
    }
}
 

output

$ java CountWords
str: I do not like green eggs and ham
count :  8

Questions answered by this page:

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




Contact: javacodex@yahoo.com