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);
StringBuffernecessary? It seems like you are using it locally within a method, thus aStringBuildermight be more fit for the job.StringBufferis useful when multiple threads are writing to the object (which is almost never the case) whilst aStringBuilderis the same object without synchronization overhead, allowing for better performance.