Search code examples
javastringbuffer

How to insert characters inside a string in Java


In my application, a user will select multiple options out of 10 options. Numbers of selected options may vary from 1 to 10. Now I am trying to separate these selected options by inserting a comma in between the numbers. I am getting the numbers like this:

 123456
 346
 12
 5

Now I am trying to convert them like this:

 1,2,3,4,5
 3,4,6
 1,2
 5(no comma)

For this I am trying StringBuffer, but I'm getting the wrong output:

 For 12 output is 1,2
 For 5 output is 5
 For 123 output is 1,,23
 For 123456 output is 1,,,,,23456

Can you help me find the mistake in my code?

String str = jTextField1.getText();
StringBuffer sb = new StringBuffer(str);
int x = 0;    
for (int i = 0; i < str.length() - 1; i++) {    
   sb.insert(++x, ",");
}
System.out.println(sb);

Solution

  • @SMA's answer works, but another solution using your code as a base is as follows:

    Your StringBuffer is growing as you are inserting commas, which makes your x index out of sync with the actual length of the buffer, therefore you'll need to increment it another time after inserting the comma.

    class Test {
    
      public static void main(String[] args) {
        String str="123456";
        StringBuffer sb=new StringBuffer(str);
        int x=0;
        for (int i = 0;i < str.length()-1; i++)
          {
            sb.insert(++x, ",");
            x += 1;
          }
          System.out.println(sb);  
        }
    
    }