Java - Write code to count Words in a string

Requirements

Write code to count Words in a string

Demo

//package com.book2s;
import java.util.regex.Pattern;

public class Main {
    public static void main(String[] argv) {
        String str = "book2s.com";
        System.out.println(countWords(str));
    }/*w w w  .ja v a2  s. c om*/

    public static int countWords(String str) {
        int words;
        char prev_char, cur_char;

        if (str.length() == 0)
            return 0;
        if (str.length() == 1)
            return Character.isWhitespace(str.charAt(0)) ? 1 : 0;

        words = 0;
        prev_char = str.charAt(0);

        for (int i = 1; i < str.length(); i++) {
            cur_char = str.charAt(i);

            // if we are at a word end
            if (Character.isWhitespace(cur_char)
                    && !Character.isWhitespace(prev_char))
                words++;

            prev_char = cur_char;
        }

        // check if we ended with a word
        if (!Character.isWhitespace(str.charAt(str.length() - 1)))
            words++;

        return words;
    }

    public static int countWords(String sentence, String separator) {
        return sentence.split(Pattern.quote(separator)).length;
    }
}

Related Example