【问题标题】:Removing the comma from the last element in the string of array [duplicate]从数组字符串中的最后一个元素中删除逗号[重复]
【发布时间】:2020-02-05 08:56:19
【问题描述】:

在打印时删除数组最后一个元素中的逗号有什么建议吗?

public static void printList(String[] words, int count) {
    for (int i=0; i < count; i++) {
        System.out.print(words[i] + ",");
    }
}

【问题讨论】:

    标签: java


    【解决方案1】:

    我喜欢处理这个问题的一种方法是有条件地前添加一个逗号,仅用于第二个单词:

    public static void printList(String[] words, int count) {
        for (int i=0; i < count; i++) {
            if (i > 0) System.out.print(",");
            System.out.print(words[i]);
        }
    }
    

    你也可以构建你想要的输出字符串,然后去掉最后的逗号:

    StringBuilder sb = new StringBuilder();
    for (int i=0; i < count; i++) {
        sb.append(words[i]).append(",");
    }
    String output = sb.toString().replaceAll(",$", "");
    System.out.println(output);
    

    【讨论】:

      【解决方案2】:

      一种快速方法:

      public static void printList(String[] words, int count) {
          for(int i = 0; i < count; i++) {
              System.out.print(words[i]);
              if(i != count-1) System.out.print(",");
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-10-02
        • 2019-01-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-10-07
        • 2015-08-05
        • 1970-01-01
        相关资源
        最近更新 更多