AldwinB AldwinB - 2 months ago 8
Java Question

How to remove last seperator in a string within a loop?

"I've searched hours for this kind of problem, but I've got no luck."





In Java, I'm try to get this kind of output:


1, 2, 3


(without the use of StringBuilder)




The result I am getting is:


1, 2, 3,


with the code:

for(int i=1; i <= 3; i++){
String output = "";
output += i + ", ";
System.out.print(output);
}





I hope someone can help me with this. Thanks in advance!

p.s I am not using any arrays for my code.

Answer

be careful where you make the final print as you have an accumulator string variable that will serve to make the impression at the end in addition also consider where you declare your variables within the variable will be created for the few times iterate the for, preferably testify before the cycle

use substring takes two parameters start position, end position

String output = "";
 for(int i=1; i <= 3; i++){
  output += i + ", ";
}
System.out.print(output.substring(0, output.length()-2)); 
//obtains from 1, 2.3 and omit the, end with the length () - 1 as the final //position

ouput

1, 2, 3

Comments