Search code examples
javastringindexoutofbounds

Method that is supposed to clean up a String throws StringIndexOutOfBoundsException


I made a method that is supposed to clean up a String. It has to delete every char with a reach of [a,z].

But I am getting this exception: StringIndexOutOfBoundsException. The moment I insert a number out of the reaching the conditions, this exception pops up.

I can't spot what I have done wrong.

    public static String kuisStringOp(String str){
        StringBuilder strb = new StringBuilder(str);
        
        for (int i = 0; i < str.length(); i++) {
            if(strb.charAt(i)<'a'||strb.charAt(i)>'z'){
                
                strb.deleteCharAt(i);
                
                
            } 
            
        }           
        return strb.toString(); 
    }

Solution

  • You are running through the entire length of your original string, but you are deleting some characters in your StringBuilder. Once you've deleted a character, your StringBuilder is shorter than your original String, and the contents have shifted to cover the deleted character. You'll eventually run off the end of the StringBuilder before you reach the end of your original String.

    Change your for loop condition to check your StringBuilder's length, and if you delete a character, another character is now in its place. Check it again by decrementing i:

    for (int i = 0; i < strb.length(); i++) {
        if(strb.charAt(i)<'a'||strb.charAt(i)>'z'){
            strb.deleteCharAt(i);
            i--;
        } 
    
    }