从C ++中的字符串解析键/值对 [英] Parsing key/value pairs from a string in C++

查看:114
本文介绍了从C ++中的字符串解析键/值对的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在C ++ 11中工作,没有Boost.我有一个函数以std :: string为输入,该std :: string包含一系列用分号分隔的键值对,并返回从输入构造的对象.所有密钥都是必需的,但可以是任何顺序.

I'm working in C++11, no Boost. I have a function that takes as input a std::string that contains a series of key-value pairs, delimited with semicolons, and returns an object constructed from the input. All keys are required, but may be in any order.

这是示例输入字符串:

Top = 0; Bottom = 6; Name = Foo;

Top=0;Bottom=6;Name=Foo;

这是另一个:

Name = Bar; Bottom = 20; Top = 10;

Name=Bar;Bottom=20;Top=10;

有一个相应的具体结构:

There is a corresponding concrete struct:

struct S 
{
    const uint8_t top;
    const uint8_t bottom;
    const string name; 
}

我已经通过在输入字符串上重复运行一个正则表达式来实现该功能,每个S成员一次,并将每个捕获的组分配给S的相关成员,但这听起来很不对劲.处理这种解析的最佳方法是什么?

I've implemented the function by repeatedly running a regular expression on the input string, once per member of S, and assigning the captured group of each to the relevant member of S, but this smells wrong. What's the best way to handle this sort of parsing?

推荐答案

对于易于阅读的解决方案,您可以例如使用 std::regex_token_iterator 和已排序的容器来区分属性值对(或者使用未排序的容器和std::sort).

For an easy readable solution, you can e.g. use std::regex_token_iterator and a sorted container to distinguish the attribute value pairs (alternatively use an unsorted container and 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.

Now the attribute value strings are sorted lexicographically in the set tokens, i.e. the first is Bottom, then Name and last Top.

最后使用简单的std::string::findstd::string::substr提取字符串的所需部分.

Lastly use a simple std::string::find and std::string::substr to extract the desired parts of the string.

实时示例

这篇关于从C ++中的字符串解析键/值对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆