将 std::string 拆分为 std::pair 的最短代码
Shortest code to split std::string into std::pair
我有一个 "key:value" 格式的文本。实际文本可能看起来像 "Server: nginx"
或 "Server:nginx"
忽略键、:
和值之间的空格。
将其拆分为 std::pair<std::string, std::string>
的最快最短方法是什么?
我会说
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'.
我会使用 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/
但是考虑到性能,您应该对上面显示的所有可能性进行速度测试(手动解析字符串,使用字符串流,正则表达式,....
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);
}
}
(live demo)
我有一个 "key:value" 格式的文本。实际文本可能看起来像 "Server: nginx"
或 "Server:nginx"
忽略键、:
和值之间的空格。
将其拆分为 std::pair<std::string, std::string>
的最快最短方法是什么?
我会说
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'.
我会使用 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/
但是考虑到性能,您应该对上面显示的所有可能性进行速度测试(手动解析字符串,使用字符串流,正则表达式,....
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);
}
}