。。还好java没有坑我

怎么统计字符串中某一单词出现的次数!急!!问问大家有没有什么好方法

参考GPT和自己的思路:好的,我可以给你提供一个解决方案。

在Java中,你可以将字符串转换成字符数组,然后遍历字符数组逐个判断单词是否匹配。可以使用indexOf()方法查找单词在字符串中的位置,如果返回值不为-1,则表示找到了该单词。

以下是示例代码:

public class WordCount {
    public static void main(String[] args) {
        String str = "Java is an object oriented programming language. Java is used in a wide range of applications.";
        String word = "Java";
        
        int count = 0;
        int index = -1;
        
        do {
            index = str.indexOf(word, index + 1);
            if (index != -1) {
                count++;
            }
        } while (index != -1);
        
        System.out.println("单词 \"" + word + "\" 出现的次数为:" + count);
    }
}

以上代码的输出结果为:

单词 "Java" 出现的次数为:2

希望这个解决方案能够帮到你!

参考GPT和自己的思路:好的,针对你的问题,我可以给出下面的代码示例来统计字符串中某一单词出现的次数:

public static int countWord(String str, String word) {
    int index = 0;
    int count = 0;
    while ((index = str.indexOf(word, index)) != -1) {
        count++;
        index += word.length();
    }
    return count;
}

其中,参数str是要统计的字符串,word是要统计出现次数的单词。函数会从字符串中查找单词,每次查找到后累加计数器。最终返回统计的次数。


public static void main(String[] args) {
        String line = "Java is an object oriented programming language. Java is used in a wide range";
        String[] arr = line.split(" ");
        Map<String, Integer> counts = new HashMap<>();
        for (String s : arr) {
            if (counts.containsKey(s)) {
                counts.put(s, counts.get(s) + 1);
            } else {
                counts.put(s, 1);
            }
        }
        for (String s : counts.keySet()) {
            System.out.println("单词" + s + "出现次数" + counts.get(s));
        }
    }