Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting a character throughout whole string

Tags:

java

string

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.

like image 368
Noob Avatar asked Nov 17 '25 22:11

Noob


2 Answers

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:

  • Insert dashes at even locations, i.e. 2*i
  • Start with an empty StringBuffer, 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.

like image 92
Sergey Kalinichenko Avatar answered Nov 20 '25 13:11

Sergey Kalinichenko


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;
}
like image 39
Dan Drews Avatar answered Nov 20 '25 12:11

Dan Drews



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!