Possible Duplicate:
Splitting a string in C++
I have this vector function from one of the answers I got on my question
vector<string> split(const string& s, char delim)
{
vector<string> elems(2);
string::size_type pos = s.find(delim);
elems[0] = s.substr(0, pos);
elems[1] = s.substr(pos + 1);
return elems;
}
However, it only accept 2 elements. How do I modify it to accept based on how many delimiter s exist in the string s?
e.g if I have this:
user#password#name#fullname#telephone
sometime the size might differ.
How can I make this function flexible to work no matter how many elements, and able to split like this function above?
Just to further explain my problem:
What i wanna achieve is the capability to split using this vector function, of the same delimiter to N size instead of fixed at size 2.
This function can only split maximum 2 element in a string, more than that result in Segmentation core dump
as previously i only have needs for usage like
user:pass
now i added more attribute so i need to be able to split
user:pass:name:department
which x[2] and x[3] will return respectively name and department
they all will be using same delimiter.
Further Update:
I tried using this function provided by 1 of the answer below
vector<string> split(const string& s, char delim)
{
bool found;
vector<string> elems;
while(1){
string::size_type pos = s.find(delim);
if (found==string::npos)break;
elems.push_back(s.substr(0, pos));
s=s.substr(pos + 1);
}
return elems;
}
and i get some error
server.cpp: In function ‘std::vector<std::basic_string<char> > split(const string&, char)’:
server.cpp:57:22: error: passing ‘const string {aka const std::basic_string<char>}’ as ‘this’ argument of ‘std::basic_string<_CharT, _Traits, _Alloc>& std::basic_string<_CharT, _Traits, _Alloc>::operator=(const std::basic_string<_CharT, _Traits, _Alloc>&) [with _CharT = char, _Traits = std::char_traits<char>, _Alloc = std::allocator<char>, std::basic_string<_CharT, _Traits, _Alloc> = std::basic_string<char>]’ discards qualifiers [-fpermissive]