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

标签 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;
  }

最佳答案

使用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

关于java - 如何不在列表的开头和结尾显示逗号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35078956/

相关文章:

java - 有没有办法用 Jackson 序列化Optional<T> 的实例?

c# - 令人惊讶的 int.ToString 输出

java - Java 中 xPath-Object 或 Document-Object 的文件路径

java - 如何从 Mac 上的 Java 连接到 MS Access 2007

java - 使用单例或依赖注入(inject)之一相对于另一种的优点和缺点

java - 初级Java(直方图)

java - LinkedList 对象如何使用 Syso 输出内容?

Android + 字符串

javascript - 调用以字符串编码的 javascript 函数

java - 如何更改此方法以返回字符串列表而不是字符串?