Reputation: 47
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
Upvotes: 1
Views: 7377
Reputation: 11710
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.
Upvotes: 5
Reputation: 1774
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);
}
Upvotes: 0
Reputation: 347214
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)
Upvotes: 1
Reputation: 279970
(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, ' ');
Upvotes: 2