0

Anytime I need to make a string from a list that has some kind of delineation I have something like

string output = "";
for(int i=0; i<array.length; i++)
    output += array[i] + ", ";
return output;

But this always adds a comma to the end where I don't want it. To avoid that I have to do

string output = "";
for(int i=0; i<array.length; i++)
    output += array[i];
    if(i != array.length - 1)
        output += ", ";
return output;

Is there a more elegant way to achieve this goal?

Coat
  • 697
  • 7
  • 18
  • 2
    what language is this? – aruisdante Oct 17 '14 at 20:05
  • 1
    @user2488335 In that case, something like this would probably be more useful: http://stackoverflow.com/questions/7682560/printing-a-comma-after-each-item-in-an-array – beaker Oct 17 '14 at 22:38
  • Wow, that's a very nice function that I never know about. I really ought to check the string library more often for things like this. Thank you for the link. – Coat Oct 18 '14 at 00:34

1 Answers1

2

One option is:

string output = array[0];
for(int i=1; i<array.length; i++)
    output += ", " + array[i];
return output;
beaker
  • 16,331
  • 3
  • 32
  • 49