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 组件:-)
添加回答
举报