从 C++ 中的字符串中解析键/值对
Parsing key/value pairs from a string in C++
我在 C++11 工作,没有 Boost。我有一个函数,它将包含一系列键值对的 std::string 作为输入,用分号分隔,并返回从输入构造的对象。所有密钥都是必需的,但可以按任意顺序排列。
下面是一个示例输入字符串:
顶部=0;底部=6;名称=福;
这是另一个:
名称=条形图;底部=20;顶部=10;
有相应的混凝土结构:
struct S
{
const uint8_t top;
const uint8_t bottom;
const string name;
}
我已经通过在输入字符串上重复运行正则表达式来实现该函数,每个 S 成员一次,并将每个成员捕获的组分配给 S 的相关成员,但这闻起来很错误。处理这种解析的最佳方法是什么?
对于易于阅读的解决方案,例如,您可以使用std::regex_token_iterator
和排序容器来区分属性值对(或者使用未排序的容器和std::sort
)。
std::regex r{R"([^;]+;)"};
std::set<std::string> tokens{std::sregex_token_iterator{std::begin(s), std::end(s), r}, std::sregex_token_iterator{}};
现在属性值字符串在集合tokens
中按字典顺序排序,即第一个是Bottom
,然后是Name
,最后一个是Top
。
最后,使用简单的std::string::find
和std::string::substr
来提取字符串的所需部分。
现场示例
你关心性能还是可读性?如果可读性足够好,那么从这个问题中选择你最喜欢的split
版本,然后我们开始:
std::map<std::string, std::string> tag_map;
for (const std::string& tag : split(input, ';')) {
auto key_val = split(input, '=');
tag_map.insert(std::make_pair(key_val[0], key_val[1]));
}
S s{std::stoi(tag_map["top"]),
std::stoi(tag_map["bottom"]),
tag_map["name"]};
相关文章:
- C++ 使用 assign 函数的字符串与直接使用 '=' 更改值的字符串之间的区别
- 对字符串进行位操作
- 对字符串进行排序时,在c++中处理sort()
- 在 c++ 中对字符串使用复制函数时打印的垃圾值
- 对字符串向量进行排序,C++具有要放在末尾的特殊值
- 如何从C++中的字符串中提取值对
- 按特定值升序对字符串进行排序.我的实施中出了什么问题?
- 是否可以创建字符串和原子<int>键值对的unordered_map?
- 使用十六进制值对标准::字符串进行编码
- 如何在使用JSON boost序列化创建JSON字符串时获取名称-值对
- 如何对字符串中的值求和
- 如何对具有十六进制值的字符串执行按字节 XOR,以 C++ 为单位
- 从 C++ 中的字符串中解析键/值对
- 如何在c++中对包含双值的字符串强制执行精度
- 以字符串形式映射键,以C++中的键值对列表形式映射值
- 按字母表对字符串数组进行排序并显示值
- 在c++ 11中不使用宏是否可以对枚举值进行字符串化?
- 从字符串中获取键/值对并存储在map中
- 提升精神:如何将值对字符串解析为map<string,string>然后返回?
- 使用C++将字符串拆分为键值对