Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to deal with last comma, when making comma separated string? [duplicate]

Possible Duplicates:
Don't print space after last number
Printing lists with commas C++

#include <vector> #include <iostream> #include <sstream> #include <boost/foreach.hpp> using namespace std;  int main() {    vector<int> VecInts;     VecInts.push_back(1);    VecInts.push_back(2);    VecInts.push_back(3);    VecInts.push_back(4);    VecInts.push_back(5);     stringstream ss;    BOOST_FOREACH(int i, VecInts)    {       ss << i << ",";    }     cout << ss.str();     return 0; } 

This prints out: 1,2,3,4,5, However I want: 1,2,3,4,5

How can I achieve that in an elegant way?

I see there is some confusion about what I mean with "elegant": E.g. no slowing down "if-clause" in my loop. Imagine 100.000 entries in the vector! If that is all you have to offer, I'd rather remove the last comma after I have gone through the loop.

like image 985
AudioDroid Avatar asked Jul 14 '11 12:07

AudioDroid


People also ask

How do I remove the last comma from a string?

To remove the last comma from a string, call the replace() method with the following regular expression /,*$/ as the first parameter and an empty string as the second. The replace method will return a new string with the last comma removed. Copied!

How do you remove duplicates from a comma separated string in python?

We can do this with the SPLIT function. This function returns a row of cells divided based on the delimiter. To remove duplicate values, we have to use the UNIQUE function. Since the UNIQUE function works for cells in different rows, we'll have to transpose our SPLIT output using the TRANSPOSE function.


2 Answers

How about this:

#include <iostream> #include <vector> #include <algorithm> #include <iterator> #include <string> #include <sstream>  int main() {    std::vector<int> v;     v.push_back(1);    v.push_back(2);    v.push_back(3);    v.push_back(4);    v.push_back(5);     std::ostringstream ss;    if(!v.empty()) {       std::copy(v.begin(), std::prev(v.end()), std::ostream_iterator<int>(ss, ", "));       ss << v.back();    }    std::cout << ss.str() << "\n"; } 

No need to add extra variables and doesn't even depend on boost! Actually, in addition to the "no additional variable in the loop" requirement, one could say that there is not even a loop :)

like image 199
Juho Avatar answered Sep 18 '22 20:09

Juho


Detecting the one before last is always tricky, detecting the first is very easy.

bool first = true; stringstream ss; BOOST_FOREACH(int i, VecInts) {   if (!first) { ss << ","; }   first = false;   ss << i; } 
like image 36
Matthieu M. Avatar answered Sep 17 '22 20:09

Matthieu M.