优雅地删除“\n” StringBuilder 中最后一个字符串后面的分隔符
有以下Java代码,用“\n”创建StringBuilder
,即回车分隔符:
while (scanner.hasNextLine()){
sb.append(scanner.nextLine()).append("\n");
}
发生过,在最后一个字符串(行)之后有“\n”符号。
如何从生成的 StringBuilder 对象中优雅地删除最后一个“\n”?
谢谢。
Have following Java code,that creates StringBuilder
with "\n",i.e. carriage return delimiters:
while (scanner.hasNextLine()){
sb.append(scanner.nextLine()).append("\n");
}
It's occurred,that after last String(line) had "\n" symbol.
How to gracefully remove last "\n" from resulting StringBuilder
object?
thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
这一直对我有用。
操作非常轻量级,保存当前内容大小的内部值只会减少 1。
此外,如果您认为缓冲区可能为空,请在执行此操作之前检查长度值。
This has always worked for me
Operation is pretty lightweight, internal value holding current content size will just be decreased by 1.
Also, check length value before doing it if you think buffer may be empty.
如果您使用的行数足够少,则可以将所有行放入
List
中,然后使用StringUtils.join(myList, "\n" );
另一种选择是
trim()
结果字符串。发现 guava 的简洁
Joiner
类:Joiner.on('\n').join(myList)
If you're working with a small enough number of lines, you can put all the lines in a
List<String>
and then useStringUtils.join(myList, "\n");
Another option is to
trim()
the resulting string.Update after discovering guava's neat
Joiner
class:Joiner.on('\n').join(myList)
您可以构建结果而无需换行符来摆脱:
You could build the result without a newline to get rid of:
sb.deleteCharAt(sb.length()-1);
sb.deleteCharAt(sb.length()-1);
您不必删除它,而可以永远不添加它。
Instead of having to remove it you could simply never add it.