"Philipp Kraus" <> wrote in message
news:ioq1lt$sba$...
> On 2011-04-21 20:28:35 +0200, Paul said:
>
>> "Philipp Kraus" <> wrote in message
>> news:iopscs$nj7$...
>>> Hello,
>>>
>>> I get a char array (out of another component) like this
>>> abcd*xyz*mnop*
>>>
>>> * is a seperator nullterm char. How can I seperate the char array at the
>>> * and push back them to a std;;vector<std::string> ?
>>>
>>> Thanks
>>>
>>
>> There is a C function called strtok() that does this.
>>
>> http://www.cplusplus.com/reference/c...string/strtok/
>
> I have tried this with the delimiter \0 but it does not work. I will get
> only the first part "abcd". On my example above I would like to get a
> result vector in this way:
> vec[0] = "abcd"
> vec[1] = "xyz"
> vec[2] = "mnop"
>
>
> Thanks for help
>
You could just do something like this:
#include <iostream>
#include <vector>
#include <string>
void splitstring(std::vector<std::string>& v, char* p, char c){
std::string str;
while (*p != '\0'){
if (*p == c){
v.push_back(str);
str.clear();
++p;
}
str+= *p;
++p;
}
if(*(str.data()) != '\0')
v.push_back(str);
}
void printvector(std::vector<std::string> v){
for (int i=0; i<v.size() ; ++i ){
std::cout<< v[i] << std::endl;
}
}
int main(){
std::vector<std::string> v1;
std::vector<std::string> v2;
char arr1[] = "abcd*xyz*mnop*";
char arr2[] = "abcd*xyz*mnop*sgegsgsgga";
splitstring(v1, arr1, '*');
splitstring(v2, arr2, '*');
std::cout<<"Printing vector v1:\n";
printvector(v1);
std::cout<<"Printing vector v2:\n";
printvector(v2);
}
The above is not perfect because if your first char is a '*' it would create
an empty string at v[0], but it may be something you can work on.