Java程序统计字符串中单词出现次数


某个单词在字符串中出现的次数表示其出现次数。举个例子,如下所示 −

String = An apple is red in colour.
Word = red
The word red occurs 1 time in the above string.

展示此程序的例子如下。

示例

 在线演示

public class Example {
public static void main(String args[]) {
String string = "Spring is beautiful but so is winter";
String word = "is";
String temp[] = string.split(" ");
int count = 0;
for (int i = 0; i < temp.length; i++) {
if (word.equals(temp[i]))
count++;
}
System.out.println("The string is: " + string);
System.out.println("The word " + word + " occurs " + count + " times in the above string");
}
}

输出

The string is: Spring is beautiful but so is winter
The word is occurs 2 times in the above string

现在让我们理解一下上述程序。

提供了字符串和单词的值。然后 temp 中的字符串被空格分隔开。使用 for 循环 来查找单词是否出现在 temp 中。每次发生这种情况,count 都会增加 1。展示此代码段的代码段如下 −

String string = "Spring is beautiful but so is winter";
String word = "is";
String temp[] = string.split(" ");
int count = 0;
for (int i = 0; i < temp.length; i++) {
if (word.equals(temp[i]))
count++;
}

显示字符串以及 count 值,即单词在字符串中出现的次数。展示此代码段的代码段如下 −

System.out.println("The string is: " + string);
System.out.println("The word " + word + " occurs " + count + " times in the above string");

更新于: 31-五月-2024

超过 13K 的浏览量

开启你的 职业

完成课程,获得认证

开始
广告