计算句子中的单词

时间:2014-07-13 19:45:59

标签: java string count words

我正在尝试编写一个程序来计算句子中的单词数。我使用split方法和String参数" "。当我输入一个字符串Hello World时,我得到一个输出:No. of words Are 1,而它应该是2。我错过了什么 ?请帮忙。

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);
    }

}


主要类

public class Main {

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

}
}

输出

Enter A String
Hello World
No. Of words are 1

1 个答案:

答案 0 :(得分:2)

在此行中,您应该按一个 空格进行拆分:

<强> Store = Sentence.split(" ");

您正在按两个 空格进行拆分。

看看这个以找到重复项:

        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));
        }
相关问题