Java Exception in Counting number of occurrences of character in a string
NickName:raduns Ask DateTime:2013-08-21T01:21:47

Java Exception in Counting number of occurrences of character in a string

I am a java beginner and want to do some logic stuffs. I have started with a simple program (i.e) to find the total number of occurrences of a character in a string. But i ended up with this exception

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 52
    at java.lang.String.charAt(Unknown Source)

And i used the following code

public class Main {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String myStr = "sofdaasdasdaofsdwerwtytuoftyutyusdfsdfsdcsadaswdeasd";
        // Counting number of occurences of 'of' in myStr
        int counter = 0;
        int totalLength = myStr.length();
        char char1;
        char char2;
        // To find of
        String myVal = "of";
        String cmpVal1;
        String cmpVal2;
        String cmpValStr;
        for (int i = 0; i < totalLength; i++) {
            char1 = myStr.charAt(i);
            cmpVal1 = Character.toString(char1);
            char2 = myStr.charAt(i + 1);
            cmpVal2 = Character.toString(char2);
            cmpValStr = cmpVal1 + cmpVal2;
            if (cmpValStr == myVal) {
                counter++;
            }

        }
        System.out.print(counter);
    }

}

Copyright Notice:Content Author:「raduns」,Reproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/18341252/java-exception-in-counting-number-of-occurrences-of-character-in-a-string

Answers
Luke Bigwood 2013-08-20T17:29:49

for (int i = 0; i < totalLength-1; i++) {\n //additional code..\n if (cmpValStr.equals(myVal)) {\n counter++;\n }\n}\n\n\nYour 'for' loop should look like that. Make sure you subtract 1 from the String's length due to your increment of char2.\n\nAlso, when comparing the two strings use the .equals()\n\nAlthough, if you're interested, this is how I would have done it:\n\nString myStr = \"sofdaasdasdaofsdwerwtytuoftyutyusdfsdfsdcsadaswdeasd\";\nint counter=0;\nfor(int i=0;i<myStr.length()-1;i++){\n if(myStr.subSequence(i, i+2).toString().contains(\"of\"))\n {\n counter++;\n }\n}\nSystem.out.print(counter);\n",


Daren 2013-08-20T17:25:10

this is your problem:\n\nchar2 = myStr.charAt(i + 1);\n\n\nyou go out of bounds with this on the last char.\n\ntry doing:\n\nfor (int i = 0; i < totalLength-1; i++)",


More about “Java Exception in Counting number of occurrences of character in a string” related questions

Java Exception in Counting number of occurrences of character in a string

I am a java beginner and want to do some logic stuffs. I have started with a simple program (i.e) to find the total number of occurrences of a character in a string. But i ended up with this except...

Show Detail

Recursion to find the number of occurrences of a specified character in a string

I have seen the solution to this question here, but the persons code is different from mine. I just want to know what I am doing wrong. I am very new to programming and desperate to be good. Quest...

Show Detail

Counting the number of occurrences of a string within a string

What's the best way of counting all the occurrences of a substring inside a string? Example: counting the occurrences of Foo inside FooBarFooBarFoo

Show Detail

Finding the number of occurrences of a character in a String [Solved]

I have a problem in my code, where I asked to find the number of occurrences of a character in a String, but I kept having an Exception errors and I don't know why? Here is my code: import java.io.

Show Detail

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=...

Show Detail

How to sort a character by number of occurrences in a String using a Map?

I wrote code that counts frequency of every character in a given string and displays it: Map&lt;Character, Integer&gt; occurrences = new HashMap&lt;&gt;(); char[] chars = str2.toCharArray(); for (c...

Show Detail

Count the number of occurrences of a character in a string for a number of queries?

I want to find the occurrences of a character in a string for n queries: For example the string is: "i_love_mathematics" and the task is to find the occurrence of: 'i' in range: 1-4(a

Show Detail

Counting the occurrences of string in Java using string.split()

I'm new to Java. I thought I would write a program to count the occurrences of a character or a sequence of characters in a sentence. I wrote the following code. But I then saw there are some ready...

Show Detail

Count the number of occurrences of a character in a string

How do I count the number of occurrences of a character in a string? e.g. 'a' appears in 'Mary had a little lamb' 4 times.

Show Detail

Count the number of occurrences of a character in a string

How do I count the number of occurrences of a character in a string? e.g. 'a' appears in 'Mary had a little lamb' 4 times.

Show Detail