共計 453 個字符,預計需要花費 2 分鐘才能閱讀完成。
在 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
。
丸趣 TV 網 – 提供最優質的資源集合!
正文完