Remove last separator from print statement

前端 未结 6 753
情深已故
情深已故 2021-01-26 09:34

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) {
            


        
6条回答
  •  醉酒成梦
    2021-01-26 09:55

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

提交回复
热议问题