单词在字符串中出现的次数表示其出现次数。一个例子如下:
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中可用。每次发生时,计数都会增加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++; }
显示字符串和计数值,即单词在字符串中出现的次数。证明这一点的代码片段如下-
System.out.println("The string is: " + string); System.out.println("The word " + word + " occurs " + count + " times in the above string");