spliting a string String in c++
I have a function MakeElementfromString( string k ){}
i want to split the string an开发者_如何学编程d make struct element{int nr, string s}
with it .
what can i use do do that ? found strtok
but couldn't use it or maybe i dont know how because is for char
and some stringstream
method.. nothing worked for me
anyone can tell me an idea ? i am not an expert in c++ so explain kind :)
thank you
If you can use libs use boost::split.
If you can't iterate over your string and put the parts in a vector.
string s("test hallo! someothertest");
char separator = ' ';
vector<string> parts;
int token_begin = 0;
for(int i = 0; i < s.size(); ++i){
if( s[i] == separator){
parts.push_back(s.substr(token_begin, i - token_begin ));
token_begin = i + 1;
}
}
//get last token if does not end with a separator
if(token_begin != s.size()){
parts.push_back(s.substr(token_begin, s.size() - token_begin));
}
At the time of this writing, the question has not been edited to say how the OP wants the string to be converted to a struct element. But this is the broad outline of how it might be done.
Assumptions: string s has first two characters that go into int member of struct and the rest of it goes into the string part.
example: s = 01hello
Pseudo-code:
string num = s.substr(0, 2);
string rest = s.substr(3);
element e;
e.setVal(num, rest);
setVal(string n, string m) {
str = m;
istringstream buffer(n);
buffer >> num;
}
where original struct is:
struct element {
int nr;
string str;
};
thank you for help made it for
struct Telem {
int nrte;
string s;
int dims;
};
and i needed to read from file a line and the line to convert into my desire element hope it helps some other people for similar problems
Telem TelemDinString( string k )
{
Telem a;
Init(a);
string buf;
stringstream ss(k);
vector<string> tokens;
while ( ss >> buf )
tokens.push_back(buf);
int nr;
stringstream convert( tokens[0] );
if ( !( convert >> nr ) )
nr=-1;
a.nrte = nr;
a.s = tokens[1];
a.dims=a.s.length();
return a;
}
精彩评论