如何不在列表的开头和结尾显示逗号

时间:2016-01-29 07:24:36

标签: java tostring

我有一个toString()方法。如何打印[A,B,C,D]而不是[,A,B,C,D,]

  public String toString()
  {
    String result = "[";

    if (numItems > 0)
    {
      for (int i = 0; i < queueArray.length && queueArray[i] != null; i++)
      {
          result+= queueArray[i].toString() + ",";
      }    
      result += "]";
    }
    else
    {
      result = "[ ]";
    } 
    return result;
  }

7 个答案:

答案 0 :(得分:3)

使用StringJoiner

public String toString() {
    StringJoiner sj = new StringJoiner(","); // Use commas to attach

    if (numItems > 0) {
        for (int i = 0; i < queueArray.length && queueArray[i] != null; i++) {
            sj.add(queueArray[i].toString()); // Loop through & attach
        }
        sj.add("]");
    } else {
        sj.add("[ ]");
    }

    return sj.toString();
}

这是另一个示例程序,以澄清它是如何工作的:

public static void main(String[] args) {
    // You pass in the "joiner" string into the StringJoiner's constructor 
    StringJoiner sj = new StringJoiner("/"); // in this case, use slashes 
    // The strings to be attached
    String[] strings = new String[]{"Hello", "World", "!"};

    for (String str : strings)
        sj.add(str); // Attach

    System.out.println(sj.toString()); // Print the content of the StringJoiner
}

输出是:

Hello/World/! // No slash in the end

答案 1 :(得分:2)

public String toString() {
    return Arrays.stream(queueArray)
            .filter(Objects::nonNull)
            .collect(Collectors.joining(",", "[", "]"));
}

答案 2 :(得分:1)

    //check whether its last item or not, to skip the appending comma at the end
    if(i==queueArray.length-1)
      result+= queueArray[i].toString();
    else
      result+= queueArray[i].toString() + ",";

OR

简单地说,

Arrays.toString(queueArray)

答案 3 :(得分:0)

Data Source=c:\test\db1.mdb

只需在for循环后添加上面的代码行,你就可以了

答案 4 :(得分:0)

您应该从i = 0迭代到数组长度-2以使用逗号连接字符串。最后一个元素比你要用昏迷来连接它。

for(int i=0; i<queueArray.length; i++) {
    result += queueArray[i].toString;
    if (i != queueArray.length-1) {
       result += ",";
    }
}

答案 5 :(得分:0)

public String toString() {
    String result = "[";
    if (numItems > 0) {
        for (int i = 0; i < queueArray.length && queueArray[i] != null; i++) {
            if(i!=0) result += ",";
            result+= queueArray[i].toString();
        }
        result += "]";
    }
    else {
        result = "[ ]";
    }
    return result;
}

答案 6 :(得分:0)

使用String.join

的一行
String result = String.format("[%s]", String.join(",", queueArray));