2

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); 
3
  • Just realised I made a really stupid mistake. Been a long day. key = query.substr(0, positionOfEquals); Commented Sep 20, 2011 at 14:57
  • Is there a question remaining after this correction? Commented Sep 20, 2011 at 15:06
  • Hmmm, I suppose the question now is, is this the best approach in terms of performance and good practice? Commented Sep 20, 2011 at 16:11

1 Answer 1

2

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); 
Sign up to request clarification or add additional context in comments.

1 Comment

To clarify for anyone who might wonder how this works: if the input string query is empty and/or does not contain =, then key will receive a copy of the entire string - because find() will return npos, which means 'no position' but in value terms contains the maximal possible index from std::size_t... and substr() stops after the input length (here npos) or at the end of the input string, whichever is first.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.