将std::string拆分为std::pair的最短代码

Shortest code to split std::string into std::pair

本文关键字:std 代码 string 拆分 pair      更新时间:2023-10-16

我有一个"key:value"格式的文本。实际文本可能看起来像"Server: nginx""Server:nginx",忽略键、:和值之间的空白。

将其分解为std::pair<std::string, std::string>的最快和最短的方法是什么?

David很接近了,但是他并没有真正测试他的代码。

这是一个工作版本。

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);
   } 
}

(现场演示)

我会使用stringstream并使用:

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);

我建议使用正则表达式(如果你的值的模式在运行时不会改变):http://www.cplusplus.com/reference/regex/

但是考虑到性能,你应该对上面显示的所有可能性(手动字符串解析,使用stringstreams,正则表达式,....

)进行速度测试。

我想说

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); } 
} 

如果分隔符是":"而不是":"

当然,你可以让代码更像面条,删除更多的行,直接使用str.find(":")而不是'index'。