Remove last separator from print statement

前端 未结 6 685
情深已故
情深已故 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 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));
    }
    

提交回复
热议问题