将逗号添加到多个元素字符串输出的更好方法是什么? [英] What is the better way to add commas to multiple elements string output?

查看:66
本文介绍了将逗号添加到多个元素字符串输出的更好方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将逗号分隔的值放入ourOutput(以供将来输出).因此,我需要添加逗号并删除最后一个不必要的逗号或检查是否应放置逗号.

I need to put comma separated values into ourOutput (for future output). So, what I need is to add commas and remove last unnecessary comma or check if comma should be placed.

我得出以下两种解决方案:

I came to two following solutions:

第一种方法:

ourOutput  = ''<<'';
for (int i = 0; i< 10, i++) {
  if (/*some condition goes here*/) {
    if (ourOutput.size() == 0) {
      ourOutput << ', '
    } 
    ourOutput << i;
  }
}

优点:不要更改结果字符串 缺点:检查每次迭代;

pros: don't change resulting string cons: check on each iteration;

第二种方法:

ourOutput  = ''<<'';
for (int i = 0; i< 10, i++) {
  if (/*some condition goes here*/) {
    ourOutput << i << ', ';
  }
}
if (ourOutput.size() != 0) {
  ourOutput.setLength(ourOutput.length() - 2);
} 

优点:不必每次都检查 缺点:修改结果字符串.

pros: don't check each time cons: modifying resulting string.

请告知,该使用哪一个,或者可能有更好的方法?

Please advise, which one to use or maybe there is some better way to do that?

p.s.用groovy编写的代码,可以随时用new StringBuilder()<<替换<<<<<<<<<<<<<<<<<<<<<<"<<< c2

p.s. code written in groovy, feel free to replace ''<<'' with new StringBuilder() and << with .append() so it became java-compilable.

推荐答案

其中,C可以是Collection,Array或Iterator.

where C can be either a Collection, Array, or Iterator.

这篇关于将逗号添加到多个元素字符串输出的更好方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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