Sinan Samet
Sinan Samet

Reputation: 6752

insert in for loop fails

I'm trying to insert in a for loop to a Stringbuilder but it crashes. This is my code

StringBuilder sb = new StringBuilder("This is a text");
for(int i = 0;i < sb.length();i++){
    if(sb.charAt(i) == 't'){
        sb.insert(i, 't');
    }
}

Purpose of this is to double every 't'.

Upvotes: 0

Views: 155

Answers (4)

Mourad BENKDOUR
Mourad BENKDOUR

Reputation: 1033

Because when you find a t this instruction sb.insert(i, 't') add t in position i and previous t become in position i+1, so when i will increment in the end of for loop with i++ you deal another time with same letter t. so that will cause infinity loop.

To fix that you should increment i with i++ in if block like that:

if(sb.charAt(i) == 't'){
sb.insert(i, 't');
i++;
}

Upvotes: 0

JFPicard
JFPicard

Reputation: 5168

I suggest to use a StringBuilder and the string like this:

String currentText = "This is a text";
StringBuilder sb = new StringBuilder();
for(int i = 0; i < currentText.length(); i++){
    sb.append(currentText.charAt(i));
    if(currentText.charAt(i) == 't'){
        sb.append('t');
    }
}

With that solution, you will not have the problem with a never ending loop.

Upvotes: 1

Emz
Emz

Reputation: 1280

The problem you are having is the following.

  1. Iterate through the list, from start to finish.
  2. If you find a t add a t.

Two scenarios, either there is at least 1 t in the String or there are none. If there are none then all will work, the code does nothing. However if there is a t it will find that t add another t, the next character to check will now be... a t!. Infinite loop.

You can go around the problem by either by incrementing i (ì++) or by using continue.

Upvotes: 0

rgettman
rgettman

Reputation: 178283

You are getting an OutOfMemoryError, because you don't skip the t character that you're doubling.

This is a text
          ^
This is a ttext
           ^
This is a tttext
            ^

This continues until you've run out of memory.

You must skip the t that you just added by incrementing i just after inserting the doubled t.

if (sb.charAt(i) == 't')
{
    sb.insert(i, 't');
    i++;
}

Upvotes: 7

Related Questions