标记然后计算该单词出现的次数
示例:“敏捷的棕色狐狸”
预期输出:
- 1 快 - 2 棕色 - 1 狐狸 - 1
public class Tokenizer
{
public static void main(String[] args)
{
int index = 0; int tokenCount;
String words[] = new String [50];
String message="The Quick brown fox the";
StringTokenizer string = new StringTokenizer(message);
tokenCount = string.countTokens();
System.out.println("Number of tokens = " + tokenCount);
while (string.hasMoreTokens())
{ words[index] = string.nextToken(); index++; }
for (index=0;index<tokenCount; index++)
{ System.out.println(words[index]); }
}
}
最佳答案
这里需要使用一个java.util.Map
来维护单词和对应的计数:
import java.util.Map;
import java.util.HashMap;
public class Tokenizer
{
public static void main(String[] args)
{
int index = 0; int tokenCount;
Map<String,Integer> wordCount = new HashMap<String,Integer>();
String message="The Quick brown fox the";
StringTokenizer string = new StringTokenizer(message);
tokenCount = string.countTokens();
System.out.println("Number of tokens = " + tokenCount);
while (string.hasMoreTokens()) {
String word = string.nextToken();
Integer count = wordCount.get(word);
if(count == null) { //this means the word was encountered the first time
wordCount.put(word, 1);
}
else { //word was already encountered we need to increment the count
wordCount.put(word, count + 1);
}
}
for (String words : wordCount.keySet())
{ System.out.println("Word : " + word + " has count :" +wordCount.get(word);
}
}
}
关于java - 使用JAVA统计一个单词出现了多少次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33729390/