除了最后一行之外,如何为所有行追加一个换行符? [英] How do I append a newline character for all lines except the last one?
本文介绍了除了最后一行之外,如何为所有行追加一个换行符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
谢谢!
解决方案
将您的思考过程从追加换行符而不是最后一次改为第一次:
boolean first = true;
StringBuilder builder = new StringBuilder(); (Map.Entry< MyClass.Key,String> entry:data.entrySet()){
if(first){
first = false;
} else {
builder.append(\\\
); //或任何您想要的$ break
$ b builder.append(entry.key())
.append(:)
.append(entry.value()) ;
}
I'm iterating through a HashMap (see my earlier question for 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.
Thanks!
解决方案
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());
}
这篇关于除了最后一行之外,如何为所有行追加一个换行符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文