Remove last separator from print statement

2019-03-05 03:15发布

问题:

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) {
            System.out.print(a+ ", ");
        }
    }

Output

1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 

Desired Output

1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15

回答1:

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(","));


回答2:

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));
}


回答3:

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+ ", ");
    }


回答4:

    public void Sort(int[] sort) {
     int i = 1;
     String str = Arrays.toString(sort);

     str = str.substring(i,str.length()-1);
     System.out.println(str);
}


回答5:

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.



回答6:

Easily can do like below:

    for (int i = 0; i < sort.length; i++) {
       System.out.print(i < sort.length-1 ?sort[i]+", " : sort[i]+"");
    }