猿问

计算 String 变量中的 indexOf 字符数

我目前正在做一个 Java 练习。我正在尝试计算String变量中字符的实例数,该变量JOptionPane使用indexOf. 到目前为止,我有这个,但它不起作用,因为在测试时计数返回该字符类型的字母数量错误。


String input_text;     

input_text = JOptionPane.showInputDialog("Write in some text");

System.out.println("Index of e in input_text: "+input_text.indexOf('e'));

然后用户需要猜测他们写的字符串中正确的字母数。我为此尝试了各种方法,但被卡住了。


陪伴而非守候
浏览 219回答 2
2回答

江户川乱折腾

String indexOf函数在这里无法解决您的问题,因为它旨在为您提供所需子字符串(在这种情况下为特定字符)第一次出现的索引。您需要遍历字符串的字符并计算与特定字符的匹配项。String input_text;&nbsp; &nbsp; &nbsp;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) {&nbsp; &nbsp; int count = 0;&nbsp; &nbsp; for(int i = 0; i < input.length(); i++) {&nbsp; &nbsp; &nbsp; &nbsp; if(input.charAt(i) == charToMatch) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; count++;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return count;}&nbsp;您还可以直接使用 Apache Commons StringUtils 的countMatches函数。此外,如果您打算在输入字符串中找到多个(不同)字符的计数,您可以为输入字符串中存在的每个字符创建一个出现计数映射,这样您就不需要遍历当询问不同字符的匹配计数时,整个字符串一次又一次。

MM们

感谢这里的所有评论,我已经设法解决了这样的字符循环public static void main(String[] args) {&nbsp; String s1="this is a sentence";&nbsp; &nbsp; char ch=s1.charAt(s1.indexOf('e'));&nbsp; &nbsp; int count = 0;&nbsp;&nbsp; &nbsp; for(int i=0;i<s1.length();i++) {&nbsp; &nbsp; &nbsp; &nbsp; if(s1.charAt(i)=='e'){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; count++;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; System.out.println("Total count of e:=="+count);}}我现在将尝试添加 JOptionPane 组件:-)
随时随地看视频慕课网APP

相关分类

Java
我要回答