Search code examples
javastringstringbuffer

Method using StringBuffer for deleting dups


I'm writing a method for deleting dups from a String using StringBuffer. The method is returning StringIndexOutOfBoundsException. How can I fix it ?

public static void removeDups( String myString ){

        StringBuffer sb = new StringBuffer( myString );
        int len =  myString.length(); 

        for ( int j = 0; j < len; j++ ){

            char c = sb.charAt(j);

            for ( int k = len - 1 ; k > j ; k-- ){

                if ( sb.charAt(k) == c ){

                    sb.deleteCharAt(k);
                    len--; 
                }

            }
        }

        System.out.println("After deleting the dups : " + sb.toString() ); 
    } 

Solution

  • for (int k = len - 1 ; k > j ; k++ )
    

    If you're trying to iterate downwards, it needs to be k--, not k++. Right now, the second iteration is going to have k = len, and that's out of bounds. You're updating upwards infinitely instead of down to a bound.

    You're also missing a bracket: it needs to be

     if ( sb.charAt(k) == c ) {
        sb.deleteCharAt(k);
        len--; 
     }
    

    (While we're at it, there is essentially no reason ever to use StringBuffer instead of StringBuilder, which provides ~the same API without synchronization overhead.)