删除StringBuilder的最后一个字符? [英] Remove last character of a StringBuilder?

查看:149
本文介绍了删除StringBuilder的最后一个字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当你必须遍历一个集合并用分隔符分隔每个数据的字符串时,你最终总会得到一个额外的分隔符,例如

When you have to loop through a collection and make a string of each data separated by a delimiter, you always end up with an extra delimiter at the end, e.g.

for(String serverId : serverIds) {
 sb.append(serverId);
 sb.append(",");
}

提供类似的内容: serverId_1,serverId_2,serverId_3,

我想删除StringBuilder中的最后一个字符(不进行转换,因为在循环之后我仍然需要它。)

I would like to delete the last character in the StringBuilder (without converting it because I still need it after this loop).

推荐答案

其他人已指出 deleteCharAt 方法,但这是另一种替代方法:

Others have pointed out the deleteCharAt method, but here's another alternative approach:

String prefix = "";
for (String serverId : serverIds) {
  sb.append(prefix);
  prefix = ",";
  sb.append(serverId);
}

或者,使用 Joiner class来自番石榴:)

从Java开始8, StringJoiner 是标准JRE的一部分。

As of Java 8, StringJoiner is part of the standard JRE.

这篇关于删除StringBuilder的最后一个字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆