Search code examples
javastringcountwords

Counting Words In A Sentence


I am trying to write a program to calculate the number of words in a sentence. I am using the split method with the String argument " ". When I enter a string say Hello World, I get an output : No. of words Are 1 while it should be 2. Did I miss something ? Please help.

import java.util.Scanner;

public class Duplicate {

String Sentence;
String Store[];

public String getString(){

    System.out.println("Enter A String");
    Scanner S = new Scanner(System.in);
    Sentence = S.nextLine();
    return Sentence;
}

public void count(){

    Store = Sentence.split("  ");
    System.out.println("No. Of words are " +Store.length);
    }

}


Main Class

public class Main {

public static void main(String args[]) {
    Duplicate D = new Duplicate();
    D.getString();
    D.count();

}
}

Output

Enter A String
Hello World
No. Of words are 1

Solution

  • In this line when you should split by one space:

    Store = Sentence.split(" ");

    You are splitting by two spaces.

    look at this to find the duplicates:

            List<String> list = Arrays.asList(text.split(" "));
    
            Set<String> uniqueWords = new HashSet<String>(list);
            for (String word : uniqueWords) {
                System.out.println(word + ": " + Collections.frequency(list, word));
            }