5

I have the following list :

vector<string> mylist;

I want to create a new string that has all the strings in mylist seperated by a comma, for years i'm writing ugly code that checks if i'm in the last string in the vector to know should i add a comma or not.

the code looks something like this :

for(unsigned int i=0;i<mylist.size(); i++)
{
    outstring+=mylist[i];
    if(i<mylist.size()-1) // Avoiding the last comma
    {
        outstring+=",";
    }
}

Is there a trick to avoid the if statement , maybe some algorithms/iterator trick using STL ?

Thanks

OopsUser
  • 4,642
  • 7
  • 46
  • 71
  • 2
    What's wrong with that solution? You have an "extra" `if`. So what? – Shoe Apr 27 '14 at 15:20
  • 3
    My (non-C++) way to do so would be to *set* `outstring` to the first item, and add a comma + next items in the loop, starting at 1. – Jongware Apr 27 '14 at 15:31
  • @Jongware You still need one more `if` to check `if (mylist.size()>0)`. :P – herohuyongtao Apr 27 '14 at 15:44
  • @herohuyongtao: that's true. Also, concatenating strings is easy. If the 'copy' operator requires more work, it's far easier to insert an `if` (then I'd rather use `if (!i) continue`). – Jongware Apr 27 '14 at 15:48

2 Answers2

7

Use boost::algorithm::join():

#include <boost/algorithm/string/join.hpp>
...
string outstring = boost::algorithm::join(mylist, ",");

Alternatively, you can use (pretty ugly actually):

stringstream  s;
copy(mylist.begin(), mylist.end(), ostream_iterator<string>(s, ","));
string outstring = s.str();  // still with the trailing delimiter ","
outstring.pop_back();        // pop back the last ","

herohuyongtao
  • 49,413
  • 29
  • 133
  • 174
1

How about taking out the last comma outside of the loop? Something like the following (Thanks to @herohuyongtao for suggesting the perfect string member function!)

for( size_t i = 0; i < mylist.size(); ++i ) {
    outstring += mylist[i];
    outstring += ",";
}

outstring.pop_back();
Arun
  • 19,750
  • 10
  • 51
  • 60