Java 如何为除最后一行之外的所有行添加换行符?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/448320/
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
How do I append a newline character for all lines except the last one?
提问by troyal
I'm iterating through a HashMap (see my earlier questionfor more detail) and building a string consisting of the data contained in the Map. For each item, I will have a new line, but for the very last item, I don't want the new line. How can I achieve this? I was thinking I could so some kind of check to see if the entry is the last one or not, but I'm not sure how to actually do that.
我正在遍历 HashMap(有关更多详细信息,请参阅我之前的问题)并构建一个由 Map 中包含的数据组成的字符串。对于每个项目,我将有一个新行,但对于最后一个项目,我不想要新行。我怎样才能做到这一点?我想我可以进行某种检查,看看条目是否是最后一个,但我不确定如何实际做到这一点。
Thanks!
谢谢!
采纳答案by Jon Skeet
Change your thought process from "append a line break all but the last time" to "prepend a line break all but the first time":
将您的思维过程从“除最后一次外附加换行符”更改为“除第一次外附加换行符”:
boolean first = true;
StringBuilder builder = new StringBuilder();
for (Map.Entry<MyClass.Key,String> entry : data.entrySet()) {
if (first) {
first = false;
} else {
builder.append("\n"); // Or whatever break you want
}
builder.append(entry.key())
.append(": ")
.append(entry.value());
}
回答by Jared
Assuming your foreach loop goes through the file in order just add a new line to every string and remove the last new line when your loop exits.
假设您的 foreach 循环遍历文件,以便在您的循环退出时向每个字符串添加一个新行并删除最后一个新行。
回答by Tiago
Not sure if this is the best, but it′s the easier way to do:
不确定这是否是最好的,但这是更简单的方法:
loop through all the values and append the \n normally in the stringbuffer. Then, do something like this
循环遍历所有值并在字符串缓冲区中正常附加 \n。然后,做这样的事情
sb.setLength(sb.length()-1);
回答by Joel Coehoorn
one method (with apologies to Jon Skeet for borrowing part of his Java code):
一种方法(向 Jon Skeet 借用他的部分 Java 代码表示歉意):
StringBuilder result = new StringBuilder();
string newline = "";
for (Map.Entry<MyClass.Key,String> entry : data.entrySet())
{
result.append(newline)
.append(entry.key())
.append(": ")
.append(entry.value());
newline = "\n";
}
回答by André
Ususally for these kind of things I use apache-commons-lang StringUtils#join. While it's not really hard to write all these kinds of utility functionality, it's always better to reuse existing proven libraries. Apache-commonsis full of useful stuff like that!
通常对于这些事情,我使用 apache-commons-lang StringUtils#join。虽然编写所有这些类型的实用程序功能并不难,但重用现有的经过验证的库总是更好。Apache-commons充满了这样的有用的东西!
回答by jan
If you use iterator instead of for...each your code could look like this:
如果您使用迭代器而不是 for...each,您的代码可能如下所示:
StringBuilder builder = new StringBuilder();
Iterator<Map.Entry<MyClass.Key, String>> it = data.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<MyClass.Key, String> entry = it.next();
builder.append(entry.key())
.append(": ")
.append(entry.value());
if (it.hasNext()) {
builder.append("\n");
}
}
回答by LukeH
Here's my succinct version, which uses the StringBuilder's length property instead of an extra variable:
这是我的简洁版本,它使用 StringBuilder 的长度属性而不是额外的变量:
StringBuilder builder = new StringBuilder();
for (Map.Entry<MyClass.Key,String> entry : data.entrySet())
{
builder.append(builder.length() > 0 ? "\n" : "")
.append(entry.key())
.append(": ")
.append(entry.value());
}
(Apologies and thanks to both Jon and Joel for "borrowing" from their examples.)
(道歉并感谢 Jon 和 Joel 从他们的例子中“借用”。)
回答by Jay R.
What about this?
那这个呢?
StringBuilder result = new StringBuilder();
for(Map.Entry<MyClass.Key,String> entry : data.entrySet())
{
builder.append(entry.key())
.append(": ")
.append(entry.value())
.append("\n");
}
return builder.substring(0, builder.length()-1);
Obligatory apologies and thanks to both Jon and Joel for "borrowing" from their examples.
必须道歉并感谢 Jon 和 Joel 从他们的例子中“借鉴”。
回答by Dexygen
This is where a join method, to complement split, would come in handy, because then you could just join all the elements using a new line as the separator, and of course it doesn't append a new line to the end of the result; that's how I do it in various scripting languages (Javascript, PHP, etc.).
这就是 join 方法来补充 split 会派上用场的地方,因为这样你就可以使用新行作为分隔符来连接所有元素,当然它不会在结果的末尾添加新行; 这就是我在各种脚本语言(Javascript、PHP 等)中的做法。
回答by akuhn
If you use Class Separator, you can do
如果你使用Class Separator,你可以做
StringBuilder buf = new StringBuilder();
Separator separator = new Separator("\n");
for (Map.Entry<MyClass.Key,String> entry: data.entrySet()) {
builder.append(separator)
.append(entry.key())
.append(": ")
.append(entry.value());
}
The separator prints in empty string upon its first use, and the separator upon all subsequent uses.
分隔符在第一次使用时打印为空字符串,在所有后续使用时打印分隔符。