MeanwhileInHell
MeanwhileInHell

Reputation: 7053

Taking key/value pair from string and storing in map

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

Answers (1)

Robᵩ
Robᵩ

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

Related Questions