简体   繁体   English

如何计算字符串中字符出现的次数?

[英]How do I count the number of occurrences of a character in a string?

System.out.print("Enter a character: ");
        String userInput= keyb.next();
        char i = userInput.charAt(0); //getting the character by itself
        int counter=0;
        for(int index= 0; index < theString.length(); index++)
        {
            char ch = userInput.charAt(index);
            if (ch==i) //comparing the chosen character to each character in the string
                counter++; //keeping track of how many times you find a match

I am brand new to programming and I have to write a program that will count the number of occurrences of a character chosen by the user in a string that is also an input. 我是编程的新手,我必须编写一个程序,该程序将计算用户在也是输入字符串中选择的字符出现的次数。 This is just the part of the program that has the problem, the error I get when running is: Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 1. Not sure what I'm doing wrong! 这只是程序中有问题的部分,运行时出现的错误是:线程“ main”中的异常java.lang.StringIndexOutOfBoundsException:字符串索引超出范围:1.不确定我在做什么错!

    for(int index= 0; index< theString.length(); index++)

Where does theString come from? theString来自哪里? I suspect you mean userInput . 我怀疑你的意思是userInput

Change To: 改成:

System.out.print("Enter a character: ");
        String userInput= keyb.next();
        char i = userInput.charAt(0);//getting the character by itself
        int counter=0;
        for(int index= 0; index< userInput.length(); index++)
        {
            char ch = userInput.charAt(index);
            if (ch==i)//comparing the chosen character to each character in the string
                counter++;//keeping track of how many times you find a match

you get the out of range because you are not iterating over the user input. 您会超出范围,因为您没有遍历用户输入。

System.out.print("Enter a character: ");
        String userInput= keyb.next();
        char i = userInput.charAt(0);//getting the character by itself
        int counter=0;
        for(int index= 0; index< theString.length(); index++)
        {
            char ch = **theString**.charAt(index);
            if (ch==i)//comparing the chosen character to each character in the string
                counter++;//keeping track of how many times you find a match

My assumption is that you want to loop through theString comparing each letter of that to the original char. 我的假设是,您要遍历theString,将其每个字母与原始char比较。 Remove the ** from theString I just added it to draw your attention to the change. 从theString中删除**,我刚刚添加了它以引起您对更改的注意。 I'm guessing theString is defined elsewhere in your code. 我猜theString是在代码的其他地方定义的。

检查堆栈跟踪中的行号,然后进行调试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM