Search code examples
javastringstringindexoutofbounds

How to check if a certain character is present in the String?


I have wrote a below code to find a keyword co_e in the below string, where _ represents any other character.

It works good if I change the String to "aaacodebbb" or "codexxcode" but if I change it to "xxcozeyycop" it throws StringIndexOutOfBoundsException

public int countCode(String str) {
    int count = 0;
    String result = "";
    boolean yes = true;
    for (int i = 0; i < str.length(); i++) {
        // yes = str.charAt(i+3);
        if (str.length() >= 3) {
            if (str.charAt(i) == 'c' && str.charAt(i + 1) == 'o' && str.charAt(i + 3) == 'e')
                count++;
        }
    }
    return (count);
}

Solution

  • In the loop, you are checking accessing i+3. So, you have to stop when i is at 4th last position.

    Replace if(str.length()>= 3) with if(str.length()>= 3 && str.length() - i >3)

    OR

    You can put the following as the first condition in your for loop:

    if(str.length() - i <=3){
        break;
    }