Here\'s a method for sorting an integer array. How can I remove the last separator form the output?
public void Sort(int[] sort) {
for (int a:sort) {
public void Sort(int[] sort) {
int i = 1;
String str = Arrays.toString(sort);
str = str.substring(i,str.length()-1);
System.out.println(str);
}
Easily can do like below:
for (int i = 0; i < sort.length; i++) {
System.out.print(i < sort.length-1 ?sort[i]+", " : sort[i]+"");
}
You may use a StringBuilder as follows:
StringBuilder sb =new StringBuilder();
int[] sort = {1,2,3,4,5,7,89,4,9,6,11,23,178,29};
for(int i : sort) sb.append(i+", ");
if(sb.length()>2) sb.delete(sb.length()-2, sb.length());
System.out.println(sb.toString());
EDIT: This is not the sorting algorythm. This is just an example of how you can present it without the last comma.
If you are using Java 8, a very clean solution is using the new StringJoiner class. This class was designed to join Strings together with a custom separator, and possibly with a prefix / suffix. With this class, you don't need to worry about deleting the last separator as you do in your snippet.
public void sort(int[] sort) {
StringJoiner sj = new StringJoiner(",");
for (int a : sort) {
sj.add(String.valueOf(a));
}
System.out.println(sj.toString());
}
You could also drop the for
loop and use Streams instead:
String str = Arrays.stream(sort).mapToObj(String::valueOf).collect(joining(","));
Couple of options:
public void Sort(int[] sort) {
for (int i = 0; i < sort.length; i++) {
System.out.print(sort[i]);
if (i < sort.length - 1) {
// not the last element. Add separator
System.out.print(" ,");
}
}
}
Another way:
public void Sort(int[] sort) {
String output = Arrays.toString(sort);
System.out.println(Arrays.toString(output).substring(1, output.length-1));
}
I think this can fix the problem just try it.
public static void sort(int[] sort) {
for (int a:sort) {
if(a==sort[sort.length-1])
System.out.println(a);
else
System.out.print(a+ ", ");
}