0

I need to delete certain chars from a stringbuilder but a couple are not deleted for some reason. This is what I have so far: I have a method with string and arraylist as paramaters. The string I'm passing is the following: "beabeefeab" and the arraylist contains the following 6 character combinations of length 2: ab, ae, af, be, bf, ef. The name of this arraylist with the combos is arrayListCombos and I walk through this arraylist in outside for loop and get the individual chars of this string combo so that I can compare the individual chars with the string char in my stringbuilder. The inside for loop is to walk through the stringbuilder and compare modString.charAt(x) with the firstChar taken from the combo. Look at first combo ab for example, firstChar=a and secondChar=b. I am able to delete the first e from string "beabeefeab"but the two consecutive e's don't get deleted and I get the following string: "babeeab" and I should get "babab" with all but a's and b's deleted. Can anyone help - I would really appreciate.

    for(int w=0;w<arrayListCombos.size();w++){
        String tempComboToKeep = arrayListCombos.get(w);
        //split up char in combo and store independantly in order to compare
        char firstChar = tempComboToKeep.charAt(0);
        System.out.println("first char: "+firstChar);
        char secondChar = tempComboToKeep.charAt(1);
        System.out.println("second char: "+secondChar);
        StringBuilder modString = new StringBuilder(s);
        //System.out.println("here is stringbuilder before modify: "+modString.toString());
        //walk through stringbuilder to find the individual chars and remove rest
        for(int x=0;x<modString.length();x++){
            //if first char is NOT equal to one of the combos, delete it
            if (modString.charAt(x) != firstChar){
                System.out.println("char not equal to firstChar: "+modString.charAt(x)+"  "+firstChar);
                //the char inside stringbuilder does not equal either of the combo chars so need to be removed
                if (modString.charAt(x) != secondChar){
                    System.out.println("char not equal to secondChar either!!!  " +
                            "DELETE this char from string builder: "+modString.charAt(x));
                    modString.deleteCharAt(x);
                }
            }
        }

1 Answers1

0

I figured out my problem. I was looping through the stringbuilder, deleting characters to this stringbuilder and trying to use this modified stringbuilder in the loop to go through all characters. To fix this I just created a new stringbuilder and used the append method and appended each time I needed to keep a character and this allowed me to continue looping with the original stringbuilder so that I don't miss any characters.