-->

Word Count In Java

This custom made method of mine counts the number of words found in a String object. I actually added another parameter for this method in case you might want to represent some other symbol for a space character. To use it, simply call

1
System.out.println(countWords(STRING_OBJECT, ' '));

Here is the code for counting the words found in a String.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public static int countWords(String s, char whitespace) {
    int numWords = 0;
    int index = 0;
    boolean prevWhiteSpace = true;
    while (index < s.length()) {
        char c = s.charAt(index++);
        boolean currWhiteSpace = (c == whitespace);
        if (prevWhiteSpace && !currWhiteSpace) {
            numWords++;
        }
        prevWhiteSpace = currWhiteSpace;
    }
    return numWords;
}

Found this post useful? Donations appreciated. Every little $ helps.

Related Posts with Thumbnails