Find Number of Words Separated by Space in a String

Two ways

1. Split the String using Space as the Separator and then calculate the length of String Array formed from the above Split.

2. Without using Split

package com.java.programs;

public class CountWords {

    public static int noOfWords(String input) {
        return input.trim().split("\\S+").length;
    }

    public static int noOfWordsWithOutSplit(String input) {
        char previous = ' ';
        int count = 0;
        for (int i = 0; i < input.length(); i++) {
            char current = input.charAt(i);
            if (i > 0 && current == ' ' && previous != ' ') {
                count++;
            }
            if (i == input.length() - 1 && current != ' ') {
                count++;
            }
            previous = current;
        }
        return count;
    }

    public static void main(String[] args) {
        System.out.println(noOfWords("This is the example for   finding number   of words in a sentence"));
        System.out.println(noOfWordsWithOutSplit("This is   the example for finding number of words    in a   sentence"));
    }

}
12
12

Related Article

All About String in Java

Leave a Reply

Your email address will not be published. Required fields are marked *