Question

Possible Duplicate:
Empty check with string split

I split the below string with '&' and saved it in a vector

const vector<string> vec = split("f0=fname0&l0=lname0&f1=fname1&l1=lname1&f2=fname2&l2=lname2&f3=&l3=","&");

Now i'm again splitting the split strings with '=' Using the below code.

vector<string> vec1;
for (std::vector<std::string>::size_type a = 0; a < vec.size(); ++a)
{
     vec1=split(vec.at(a),"=");

}

At last I'm getting only the last item of the vector 'vec' to 'vec1'. every time my vec1 pointer refreshing. But i want to add splitted string in last position of the vec1. How can i do this ?

Was it helpful?

Solution

You assign to vec1 every time in the loop, so it will only contain the last pair. Instead you should append to vec1. This is done simplest with the insert function:

vector<string> vec1;
for (std::vector<std::string>::size_type a = 0; a < vec.size(); ++a)
{
    vector<string> tmp = split(vec.at(a),"=");
    vec1.insert(vec1.end(), tmp.begin(), tmp.end());
}

OTHER TIPS

Do you understand what a vector is? It does not make alot of sence, to split the string and put it into one vector "space" alltogether again (you could have just kept the string then)

I guess you are using boost's split() function.. then just skip the for loop and just call

const vector<string> vec = split("f0=fname0&l0=lname0&f1=fname1&l1=lname1&f2=fname2&l2=lname2&f3=&l3=","&");

for( int i = 0; i <= vec.size(); i++){
cout << i << "#: " << vec.at(i) << endl;
} 

to see the vectors contents (at index)

That's because you are assigning to vec1 instead of appending. You are replacing contents generated previously and ending up with result of last iteration (you could fix it by using vec1.push_back()).

So, you want to get a vector of strings with parameters, but how you gonna determine which value belongs to which parameter. IMO, you better use std::map:

using std::string;
using std::vector;
using std::map;

vector<stirng> vec = split("f0=fname0&l0=lname0&f1=fname1&l1=lname1&f2=fname2&l2=lname2&f3=&l3=","&");

map<string, string> params;

for (auto it = vec.begin(); it != vec.end(); ++it) {
    vector<string> p = split(*it, "=");
    params.insert(p[0], p[1]);
}

Now you will have list of keys with it's values inside of params, so you will be able to params["f0"].

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top