1

Basically, (dog)(cat)(mouse) needs to be (dog) (cat) (mouse).

My attempted code:

StringBuilder sb = new StringBuilder("(dog)(cat)(mouse)");

for (int i = 0; i < sb.length(); i ++)
{
   if (sb.charAt(i) == ')')
   {
      sb.insert(i, ' ');
   }
}

String result = sb.toString();

But I'm getting some sort of "Java heap space" error

5
  • 4
    Where does sb.insert(i, ' '); insert the space? Commented Feb 23, 2015 at 23:45
  • 2
    This is partly because the one the loop encounters the first ), it adds a space BEFORE it, so on the next iteration, it will find another ) (creating something like " )"). You could see this if you add a System.out.println after each iteration Commented Feb 23, 2015 at 23:49
  • @sotirios After the found index of the closing parentheses Commented Feb 23, 2015 at 23:49
  • @MadProgrammer I think it happens the first time it encounters the ) but you have the idea right. Commented Feb 23, 2015 at 23:50
  • @soong True, I jumped to the last one cause it was obvious Commented Feb 23, 2015 at 23:50

4 Answers 4

5

You could try:

String string = "(dog)(cat)(mouse)";
string = string.replace(")(", ") (");

This replaces all occurrences of ")(" with ") (".

But if you want to do it your way, the fix will be to increment i using i++; right before you insert, since you are inserting a space before your bracket, not after it.

Sign up to request clarification or add additional context in comments.

3 Comments

This is just me, but I really don't like modifying the loop variable within loops, it can really hard to debug if problems arise, but that's me :P
Until you have to replace A with AA and it blows up for the same reason as the question. There's no problem with changing loop variables within loops, especially if you're advancing them. But to each their own :)
As I said, it's just me - I don't like doing it because it's unobvious (and easy to miss), bit like placing a return statement in the middle of your method. It's really easy to miss and lose the context of what's going on. Don't say you shouldn't do it, just that it creeps me out and has it's own set of issues ;)
2
(dog)(ca
01234567

You invoke

  sb.insert(i, ' ');

with i == 4. insert takes everything at the current offset shifts it right by 1 and inserts the given characters. So

(dog )(ca
012345678

Then you loop again, and now i++ becomes 5, where there is the previous ), so you do the same thing and add a space before it.

(dog  )(ca
0123456789

You keep repeating this until you run out of heap space.

Add the space after the ).

 sb.insert(i + 1, ' ');

Comments

1

So, basically, when the loop encounters the first ) character, it inserts a space at the exact position of i (where the ) currently is), this effectively adds the space BEFORE the ) character.

On the next loop, it will encounter the same ) character and the process repeats until you run out of memory...

Instead, you want to use i + 1 to insert the space AFTER the ) character, for example...

    StringBuilder sb = new StringBuilder("(dog)(cat)(mouse)");

    for (int i = 0; i < sb.length(); i++) {
        if (sb.charAt(i) == ')') {
            sb.insert(i + 1, ' ');
        }
    }

    String result = sb.toString().trim();
    System.out.println(result);

Which outputs

(dog) (cat) (mouse)

Comments

0

I've added the space after the bracket (i+1). The reason for the heap error was that you were increasing the length of sb overtime you did an insert.

public static void main(String[] args) {
    StringBuilder sb = new StringBuilder("(dog)(cat)(mouse)");
    int length =  sb.length();

    for (int i = 0; i < length; i ++)
    {
       if (sb.charAt(i) == ')')
       {
         sb.insert(i+1, " ");
       }
    }

    String result = sb.toString();
    System.out.println(result);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.