我正在尝试编写一个程序来计算句子中的单词数。我正在将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
最佳答案
在这一行中,应将一个空格分开: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));
}
关于java - 句子中的单词数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24726512/