4

I have a text, in "key:value" format. The actual text may look like, "Server: nginx" or "Server:nginx" ignoring the whitespaces between the key, : and value.

What could be the fastest and shortest way to split this into a std::pair<std::string, std::string>?

quarks
  • 33,478
  • 73
  • 290
  • 513

4 Answers4

6

David was close, but he didn't actually test his code.

Here's a working version.

auto index = str.find(':');
std::pair<std::string,std::string> keyVal;
if (index != std::string::npos) {

   // Split around ':' character
   keyVal = std::make_pair(
      str.substr(0,index),
      str.substr(index+1)
   );

   // Trim any leading ' ' in the value part
   // (you may wish to add further conditions, such as '\t')
   while (!keyVal.second.empty() && keyVal.second.front() == ' ') {
      keyVal.second.erase(0,1);
   } 
}

(live demo)

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
1

I would use a stringstream and use:

string str = "Server: nginx with more stuff";
std::string key, val;
std::stringstream ss(str);
std::getline(ss, key, ':');
std::getline(ss, val);
auto p = make_pair(key, val);
if (p.second.front() = ' ') // get rid of leading space if it exist
    p.second.erase(0, 1);
NathanOliver
  • 171,901
  • 28
  • 288
  • 402
0

I'd say

auto index = str.find(":");
std::pair<std::string,std::string> keyVal
if (index != std::string::npos){
 keyVal = std::make_pair( str.substr(0,str.size()-index),
 str.substr(index+1, std::string::npos));
 if (keyVal.second.front() == ' ') {keyVal.second.erase(0,1); } 
} 

this will remove the whitespace if the seperator is ": " instead of ":"

of course , you can make the code spaggetier and remove even more line and use str.find(":") directly instead of 'index'.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
David Haim
  • 25,446
  • 3
  • 44
  • 78
0

I would recommend the usage of regular expressions (if the pattern of your values won't change at runtime): http://www.cplusplus.com/reference/regex/

But in concern of performance you should make speed tests for all the possibilities which are showed above (string parsing manually, using stringstreams, regular expressions,....

mbed_dev
  • 1,450
  • 16
  • 33