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:
1st approach:
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;
2nd approach:
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. code written in groovy, feel free to replace ”<<” with new StringBuilder() and << with .append() so it became java-compilable.
There’s an excellent library to aid you with this, Commons Lang StringUtils
where
Ccan be either a Collection, Array, or Iterator.