I have a StringBuffer 'buftext' that contains some text. I need to insert another text 'insertnew' before a given character 'before'. Every time I insert the text the length of the StringBuffer increases and that messes up my if part:
int buflength = buftext.length(); for(int i = 0; i < buflength; i++) { String compare = buftext.substring(i,i+1); if(compare.equals(before)) { buftext.insert(i,insertnew); buflength = buftext.length(); } }
I get an infinite loop. Why does this happen and how can I solve it?
This happens because: You are inserting new text at a specified position, but in the next iteration you are getting the same 'compare' where you had inserted text in the previous iteration. That means the loop never gets past the first encounter with 'compare' and keeps finding it again and inserts text infinitely.
You must increase the counter 'i' with the length of the inserted text as well as the string with which you are comparing (so that you don't encounter it in the next iteration).