0
public static String RemoveChar(String s,char a,char b)
    {
        StringBuilder sb = new StringBuilder(s);
        for(int i=0;i < sb.length();i++)
        {
            if(sb.charAt(i)==a || sb.charAt(i)==b)
            {   System.out.println("Characters removed are : "+a+" "+b);
                System.out.println("Removed character at "+i+" : "+s.charAt(i));
                sb.deleteCharAt(i);

            }
        }
        return sb.toString();
    }



    **Input** :  RemoveChar("beabeefeab",'a','b');
    **Output** : Characters removed are : a b
    Removed character at 0 : b
    Characters removed are : a b //It checks if the character at the index is a or b
    Removed character at 1 : e //after it passes the if condition it removes e.Why does this happen? What alternative can i do for this?
    Characters removed are : a b
    Removed character 6 : f
    ebeefeb

I am new to stringbuilder and java so excuse me if this is a silly question.Suggest an alternative and tell me what went wrong here.It would be really helpful for this beginner :)

  • 1
    when you want to remove characters as you loop it's better to loop from the end to the front e.g. `for(int i=sb.length()-1;i >= 0 ;i--){...}` – Ousmane D. Jun 11 '18 at 18:43
  • Based on what you seem to be trying to do, see [Remove all occurrences of char from string](https://stackoverflow.com/q/4576352) or [replace list of characters in a string](https://stackoverflow.com/q/8154377) – Bernhard Barker Jun 11 '18 at 18:50

2 Answers2

0

When you call deleteCharAt you delete the character at index i which shifts the rest of the characters to the left by one position. So, in this case, you should not increment the index counter i by one.

Try this

for(int i=0; i < sb.length() ; )
    {
        if(sb.charAt(i)==a || sb.charAt(i)==b)
        {   System.out.println("Characters removed are : "+a+" "+b);
            System.out.println("Removed character at "+i+" : "+sb.charAt(i));
            sb.deleteCharAt(i);
        } else {
           i++;
        }
    }
Thiyagu
  • 17,362
  • 5
  • 42
  • 79
0

After you delete the character at index i, the character that used to be in position i + 1 is now in position i, and the character that used to be at i + 2 is now at i + 1. Afterwards, you increment i, so you're looking at the character that used to be in index i + 2, and skipped the character at index i+1.

Easy solutions include iterating backwards, or doing i-- inside your if.

Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413