Java 代码统计文本中单词出现频率 - 以 'what' 为例
以下是使用 split 和 equals 方法统计句子中单词'what'出现的频率的示例代码:
public class WordFrequency {
public static void main(String[] args) {
String words = 'Accept what was and what is, and you'll have more positive energy to pursue what will be.';
String[] wordArray = words.split('\s+'); // 使用空格分割句子得到单词数组
int frequency = 0; // 统计频率的变量
for (String word : wordArray) {
if (word.equals('what')) { // 判断单词是否等于'what'
frequency++; // 频率加一
}
}
System.out.println('The word 'what' appears ' + frequency + ' times.');
}
}
输出结果为: The word 'what' appears 3 times.
原文地址: http://www.cveoy.top/t/topic/bmgm 著作权归作者所有。请勿转载和采集!