int[] number = {10, 20, 30, 40, 50};
for (int numb : numb) {
System.out.print(numb);
System.out.print(",");
}
need to resolve this in this kind of form
10,20,30,40,50
without the last character that is used
int[] number = {10, 20, 30, 40, 50};
for (int numb : numb) {
System.out.print(numb);
System.out.print(",");
}
need to resolve this in this kind of form
10,20,30,40,50
without the last character that is used
Yes. The easiest way would be a traditional for
loop;
int[] number = {10, 20, 30, 40, 50};
for (int i = 0; i < number.length; i++) {
if (i != 0) {
System.out.print(",");
}
System.out.print(number[i]);
}
You might also use a StringJoiner
or stream concatenation. But that would be more complicated than just using a regular for
loop as above.
Build that string using a StringJoiner
:
int[] number = {10, 20, 30, 40, 50};
StringJoiner joiner = new StringJoiner(",");
for (int numb : number)
joiner.add(String.valueOf(numb));
String s = joiner.toString();
System.out.println(s); // prints: 10,20,30,40,50
There are a few ways you could handle it.
You could use a "manual" for loop:
for (int i = 0; i < number; ++i) {...
... and then treat the case of when i + 1 == number.length
as a special case.
You could also use IntStream
, map that to a Stream
using mapToObj
, and then collect that stream using Collectors.joining(",")
:
String s = Stream.of(number)
.mapToObject(Integer::toString)
.collect(Collectors.joining(","));
System.out.print(s);
But the easiest way is probably to use Arrays.toString(int[])
. That will produce a string with a space after each comma, but you can then do replaceAll(" ", "")
to remove that.