+ 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
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.
+ 1
you're awesome! it worked! ty so much!
+ 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.
+ 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).