将逗号添加到多个元素字符串输出的更好方法是什么? [英] What is the better way to add commas to multiple elements string output?
问题描述
我需要将逗号分隔的值放入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.