Count words in a string method?

I was wondering how I would write a method to count the number of words in a java string only by using string methods like charAt, length, or substring.

Loops and if statements are okay!

I really appreciate any help I can get! Thanks!


Solution 1:

This would work even with multiple spaces and leading and/or trailing spaces and blank lines:

String trim = s.trim();
if (trim.isEmpty())
    return 0;
return trim.split("\\s+").length; // separate string around spaces

Hope that helps. More info about split here.

Solution 2:

public static int countWords(String s){

    int wordCount = 0;

    boolean word = false;
    int endOfLine = s.length() - 1;

    for (int i = 0; i < s.length(); i++) {
        // if the char is a letter, word = true.
        if (Character.isLetter(s.charAt(i)) && i != endOfLine) {
            word = true;
            // if char isn't a letter and there have been letters before,
            // counter goes up.
        } else if (!Character.isLetter(s.charAt(i)) && word) {
            wordCount++;
            word = false;
            // last word of String; if it doesn't end with a non letter, it
            // wouldn't count without this.
        } else if (Character.isLetter(s.charAt(i)) && i == endOfLine) {
            wordCount++;
        }
    }
    return wordCount;
}

Solution 3:

Hi I just figured out with StringTokenizer like this:

String words = "word word2 word3 word4";
StringTokenizer st = new Tokenizer(words);
st.countTokens();

Solution 4:

Simply use ,

str.split("\\w+").length ;