Remove last separator from print statement

前端 未结 6 670
情深已故
情深已故 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:47
        public void Sort(int[] sort) {
         int i = 1;
         String str = Arrays.toString(sort);
    
         str = str.substring(i,str.length()-1);
         System.out.println(str);
    }
    
    0 讨论(0)
  • 2021-01-26 09:48

    Easily can do like below:

        for (int i = 0; i < sort.length; i++) {
           System.out.print(i < sort.length-1 ?sort[i]+", " : sort[i]+"");
        }
    
    0 讨论(0)
  • 2021-01-26 09:52

    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.

    0 讨论(0)
  • 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(","));
    
    0 讨论(0)
  • 2021-01-26 10:03

    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));
    }
    
    0 讨论(0)
  • 2021-01-26 10:03

    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+ ", ");
        }
    
    0 讨论(0)
提交回复
热议问题