Remove last separator from print statement

♀尐吖头ヾ 提交于 2019-12-20 05:47:52

问题


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


来源:https://stackoverflow.com/questions/33718292/remove-last-separator-from-print-statement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!