Hi I'm trying to insert a dash in between all of the characters in a string. I've done this, but it wont work:
public static String expand (String word)
{
int stringLength = word.length();
for (int x=0; x<stringLength; x++){
word = new StringBuffer(word).insert(x, "-").toString();
}
return word;
}
It results in the dashes before the word. I don't understand why it's not working. Thanks.
That's right, all dashes get inserted before the word. Here is how this happens: when you insert the first dash, what used to be at index one is moved by one character, so when you insert the dash at the next position, you insert it right after the previous dash: the word keeps moving away, so you loop behaves like a dog chasing its own tail!
There are several ways to fix this problem:
2*iStringBuffer, go through the original characters in a loop, and add a character followed by a dash; when you are at the last character, do not add a dash.Note that the second approach is more efficient, because it is linear in the number of characters in the original word. The first approach (i.e. one based on insertions) is less efficient, because it is O(n2) due to the need to shift the tail of the buffer on each insertion.
The issue is that you are adding a new character into the string, but not incrementing the index to account for that.
Try this (note, I haven't tested it, but it should work correctly. If you have an extra dash at start or finish, just remove them afterward):
public static String expand (String word)
{
int stringLength = word.length();
for (int x=1; x<(stringLength-1)*2; x+=2){
word = new StringBuffer(word).insert(x, "-").toString();
}
return word;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With