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 的瀏覽量

開啟你的 職業

完成課程,獲得認證

開始
廣告
© . All rights reserved.