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

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

问题描述

我正在遍历 HashMap(参见 我之前的问题 了解更多详细信息)并构建一个由 Map 中包含的数据组成的字符串.对于每个项目,我将有一个新行,但对于最后一个项目,我不想要新行.我怎样才能做到这一点?我想我可以进行某种检查,看看条目是否是最后一个,但我不确定如何实际做到这一点.

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.

谢谢!

推荐答案

将您的思维过程从除最后一次外添加换行符"更改为除第一次外添加换行符":

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("
"); // Or whatever break you want
    }
    builder.append(entry.key())
           .append(": ")
           .append(entry.value());
}

这篇关于如何为除最后一行之外的所有行添加换行符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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