gpt4 book ai didi

java - 使用JAVA统计一个单词出现了多少次

转载 作者:行者123 更新时间:2023-12-01 10:53:28 25 4
gpt4 key购买 nike

标记然后计算该单词出现的次数

示例:“敏捷的棕色狐狸”

预期输出:

- 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com