繁体   English   中英

如何在java中删除字符串末尾的多余逗号?

[英]How would it be possible to remove extra comma at the end of a string in java?

public Image addComments(String createComments) {
    comments.append(createComments + ",");
    return this;
}

这就是我得到的,A,B,

这就是我想要的样子:A,B

我尝试使用正则表达式createComments = createComments.replaceAll(",$", ""); 但它没有用。

如果commentsStringBuilder (或StringBuffer ),则可以避免添加尾随逗号:

public Image addComments(String createComments) {
    if (comments.length() > 0) comments.append(",");
    comments.append(createComments);
    return this;
}

我认为您可以使用任何 Collection 和 String.join 来避免整个逗号情况

Collection<String> comments = Arrays.asList("A", "B", "C", "D");

final String joinedComments = String.join(",", comments);

System.out.println(joinedComments);

这将返回

A,B,C,D

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM