Reputation: 7053
What is the best way to split a string in two? I have this but can't get 'name' right as the substr doesnt allow me to set where to start from and where to finish, only where to start from and for how many characters (which is unknown to me):
string query = "key=value";
string key;
string value;
int positionOfEquals = query.find("=");
key = query.substr(0, positionOfEquals );
value = query.substr(positionOfEquals + 1);
Upvotes: 2
Views: 3951
Reputation: 168626
Yours is a fine approach, but you still have one bug. What if there is no '='
?
string query = "key=value";
string key;
string value;
int positionOfEquals = query.find("=");
key = query.substr(0, positionOfEquals );
if(positionOfEquals != string::npos)
value = query.substr(positionOfEquals + 1);
Upvotes: 2