StringBuffer does not delete double 'x' char | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

StringBuffer does not delete double 'x' char

i want to delete all the "x" letters in the string, but if 2 or more "x" are adjacent, it does not work. here is my code. StringBuffer sb = new StringBuffer("xx bla bla xx"); for(int i=0; i<=sb.length()-1; i++) { if(sb.charAt(i)=='x'||sb.charAt(i)=='X') { sb.deleteCharAt(i); } } System.out.println(sb); output: x bla bla x

5th May 2019, 1:14 AM
mhrdzgn
4 Answers
+ 6
In body of your if statement add --i; and it will work. Every time you delete x, you change your string. After first iteration it will be : sb= x bla bla xx In second iteration your i=1, but in sb "x" has index 0 and " " has index 1 so it will not delete it.
5th May 2019, 2:04 AM
voja
voja - avatar
+ 1
you're awesome! it worked! ty so much!
5th May 2019, 1:44 AM
mhrdzgn
+ 1
Is this Java? I think whats happening is when you delete 1 x all the following letters move forward by 1. Then you move forward 1 char, which is 2 chars relative to the original string. So every second x will get skipped in a sequence of x chars.
5th May 2019, 1:46 AM
Jared Bird
Jared Bird - avatar
+ 1
Serena Yvonne You don't need the if(i!=0). If its the first iteration, i=0. After deleting the x, i=-1; End of the for loop. i=0; will check the first char again (which is what you want).
5th May 2019, 2:40 AM
Jared Bird
Jared Bird - avatar