除了最后一行之外,如何为所有行追加一个换行符? [英] How do I append a newline character for all lines except the last one?

查看:112
本文介绍了除了最后一行之外,如何为所有行追加一个换行符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在遍历一个HashMap(请参阅),并构建一个由Map中包含的数据组成的字符串。对于每个项目,我将有一个新的线,但对于最后一个项目,我不想要新的线。我怎样才能做到这一点?我想我可以这样检查一下,看看这个入口是不是最后一个,但我不知道如何去做。



谢谢!

解决方案

将您的思考过程从追加换行符而不是最后一次改为第一次:

  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屋!

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