以下是使用 split 和 equals 方法统计句子中单词'what'出现的频率的代码示例:

public class WordFrequency {
    public static void main(String[] args) {
        String sentence = "Accept what was and what is, and you'll have more positive energy to pursue what will be.";
        String[] words = sentence.split(" "); // 分割句子为单词数组
        
        int frequency = 0; // 统计频率的变量
        
        for (String word : words) { // 遍历单词数组
            if (word.equals("what")) { // 判等并统计
                frequency++;
            }
        }
        
        System.out.println("Frequency of 'what': " + frequency);
    }
}

输出结果:

Frequency of 'what': 3
Java 代码示例:统计文本中单词频率

原文地址: https://www.cveoy.top/t/topic/bmf1 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录