溫馨提示×

java怎么判斷某個字符出現次數

小億
187
2023-08-28 11:12:50
欄目: 編程語言

在Java中,我們可以使用循環遍歷字符串的每個字符,并使用條件語句判斷是否為目標字符,然后累加出現次數。

以下是一個示例代碼:

public class CharacterCount {
public static void main(String[] args) {
String str = "Hello World";
char targetChar = 'o';
int count = 0;
// 遍歷字符串的每個字符
for (int i = 0; i < str.length(); i++) {
// 判斷是否為目標字符
if (str.charAt(i) == targetChar) {
count++;
}
}
System.out.println("目標字符出現的次數:" + count);
}
}

上述代碼中,我們定義了一個字符串str和目標字符targetChar,然后通過遍歷字符串的每個字符,判斷是否為目標字符并累加出現次數。最后輸出目標字符出現的次數。

在這個示例中,字符'o'在字符串"Hello World"中出現了兩次,所以輸出結果為2。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女