2 回答

TA貢獻1851條經驗 獲得超5個贊
String indexOf函數在這里無法解決您的問題,因為它旨在為您提供所需子字符串(在這種情況下為特定字符)第一次出現的索引。
您需要遍歷字符串的字符并計算與特定字符的匹配項。
String input_text;
input_text = JOptionPane.showInputDialog("Write in some text");
System.out.println("Index of e in input_text: "+ getMatchCount(input_text, 'e'));
int getMatchCount(String input, char charToMatch) {
int count = 0;
for(int i = 0; i < input.length(); i++) {
if(input.charAt(i) == charToMatch) {
count++;
}
}
return count;
}
您還可以直接使用 Apache Commons StringUtils 的countMatches函數。
此外,如果您打算在輸入字符串中找到多個(不同)字符的計數,您可以為輸入字符串中存在的每個字符創建一個出現計數映射,這樣您就不需要遍歷當詢問不同字符的匹配計數時,整個字符串一次又一次。

TA貢獻1886條經驗 獲得超2個贊
感謝這里的所有評論,我已經設法解決了這樣的字符循環
public static void main(String[] args) {
String s1="this is a sentence";
char ch=s1.charAt(s1.indexOf('e'));
int count = 0;
for(int i=0;i<s1.length();i++) {
if(s1.charAt(i)=='e'){
count++;
}
}
System.out.println("Total count of e:=="+count);
}
}
我現在將嘗試添加 JOptionPane 組件:-)
添加回答
舉報