java 在 StringBuilder 中的最后一个字符串之后优雅地删除“\n”分隔符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3949670/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Gracefully remove "\n" delimiter after last String within StringBuilder
提问by sergionni
Have following Java code,that creates StringBuilder
with "\n",i.e. carriage return delimiters:
有以下Java代码,StringBuilder
用“\n”创建,即回车分隔符:
while (scanner.hasNextLine()){
sb.append(scanner.nextLine()).append("\n");
}
It's occurred,that after last String(line) had "\n" symbol.
发生了,在最后一个字符串(行)之后有“\n”符号。
How to gracefully remove last "\n" from resulting StringBuilder
object?
如何从结果StringBuilder
对象中优雅地删除最后一个“\n” ?
thanks.
谢谢。
回答by Nikita Rybak
This has always worked for me
这一直对我有用
sb.setLength(sb.length() - 1);
Operation is pretty lightweight, internal value holding current content size will just be decreased by 1.
操作非常轻量级,保持当前内容大小的内部值只会减少 1。
Also, check length value before doing it if you think buffer may be empty.
此外,如果您认为缓冲区可能为空,请在执行此操作之前检查长度值。
回答by oksayt
If you're working with a small enough number of lines, you can put all the lines in a List<String>
and then use StringUtils.join(myList, "\n");
如果您使用的行数足够少,则可以将所有行放在 a 中List<String>
,然后使用StringUtils.join(myList, "\n");
Another option is to trim()
the resulting string.
另一种选择是trim()
结果字符串。
Update after discovering guava's neat Joiner
class:
发现guava的整洁Joiner
类后更新:
Joiner.on('\n').join(myList)
Joiner.on('\n').join(myList)
回答by rsp
You could build the result without a newline to get rid of:
您可以在没有换行符的情况下构建结果以摆脱:
String separator = "";
while (scanner.hasNextLine()){
sb.append(separator).append(scanner.nextLine());
separator = "\n";
}
回答by cherouvim
Instead of having to remove it you could simply never add it.
您可以永远不添加它,而不必删除它。
while (scanner.hasNextLine()) {
if (sb.length()>0) sb.append("\n");
sb.append(scanner.nextLine());
}
回答by Stephen Swensen
bool isFirst = true;
while (scanner.hasNextLine()){
if(!isFirst)
sb.append("\n"));
else
isFirst = false;
sb.append(scanner.nextLine());
}
回答by Mikos
sb.deleteCharAt(sb.length()-1);
sb.deleteCharAt(sb.length()-1);
回答by andersoj
if (scanner.hasNextLine())
sb.append(scanner.nextLine());
while (scanner.hasNextLine()){
sb.append("\n").append(scanner.nextLine());
}