将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>
的最快和最短的方法是什么?
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'。
相关文章:
- 为什么在C的循环中使用printf的Rust代码不显示输出,而在C++的循环中显示std::cout
- "std::forward"和"std::move"真的不生成代码吗?
- 使用 std::vector C++快速排序,EXC_BAD_ACCESS代码 2
- std::string == 运算符在代码中不起作用
- 为什么 std::invocable 概念阻止了此代码的编译
- 如何防止使用 std::shared_ptr 的代码中的内存泄漏
- "p"数组如何使用 std::normal_distribution 存储以下代码中的值C++?
- 为什么使用 std::vector 的代码不能编译,但使用 std::unique_ptr 如果没有 noexcept
- 如何处理给定代码中的 std::out_of_range 错误?
- 在带有模板的函数中传递未知大小的 std::数组.如何更正此代码?
- 如何使用 GDB 从功能C++逐步调试到 std::function 用户代码?
- 避免使用 std::any 编写相同的重复类型检查代码
- 示例代码中使用分隔符将 std::string 拆分为 std::vector 的范围问题
- 使用 std::chrono::steady_clock 对线程/异步中的代码进行基准测试
- std::mutex::lock() 产生奇怪(和不必要的)ASM 代码
- 如何在数组类型的模板代码中计算std::size_t
- 将json代码格式化为std::string
- std::out_of_range 使用 libserial 库的 C++ 代码中的错误
- 为什么代码使用 std::map 无法编译?
- 这段 C++ 代码的奇怪行为(std::wcout 和 std::exception)