Parsing key/value pairs from a string in C++

前端 未结 2 364
情书的邮戳
情书的邮戳 2021-01-20 23:31

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

相关标签:
2条回答
  • 2021-01-21 00:00

    Do you care about performance or readability? If readability is good enough, then pick your favorite version of split from this question and away we go:

    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"]};
    
    0 讨论(0)
  • 2021-01-21 00:02

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

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

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

    Live example

    0 讨论(0)
提交回复
热议问题