Несколько подстрок между одинаковыми разделителями - PullRequest
0 голосов
/ 29 сентября 2018

Я новичок в c ++ и хотел бы знать, как извлечь несколько подстрок из одной строки между одинаковыми разделителями?

ex.

"{(" id ":" 4219 "," firstname ":" Paul "), (" id ":" 4349 "," firstname ":"Джо"), ("id": "4829", "firstname": "Brandy")} "

Я хочу идентификаторы:

4219, 43494829

Ответы [ 2 ]

0 голосов
/ 29 сентября 2018

Вы можете использовать регулярные выражения для соответствия идентификаторам:

#include <iostream>
#include <regex>

int main() {
    // This is your string.
    std::string s{ R"({("id":"4219","firstname":"Paul"),("id":"4349","firstname":"Joe"),"("id":"4829","firstname":"Brandy")})"};

    // Matches "id":"<any number of digits>"
    // The id will be captured in the first group
    std::regex r(R"("id"\s*:\s*"(\d+))");

    // Make iterators that perform the matching
    auto ids_begin = std::sregex_iterator(s.begin(), s.end(), r);
    auto ids_end = std::sregex_iterator();

    // Iterate the matches and print the first group of each of them
    // (where the id is captured)
    for (auto it = ids_begin; it != ids_end; ++it) {
        std::smatch match = *it;
        std::cout << match[1].str() << ',';
    }

}

Смотрите его в прямом эфире на Coliru

0 голосов
/ 29 сентября 2018

Ну, вот взлом q & d:

#include <iostream>
#include <sstream>
#include <string>

int main()
{
    std::string s{ "{(\"id\":\"4219\",\"firstname\":\"Paul\"),"
                    "(\"id\":\"4349\",\"firstname\":\"Joe\"),"
                    "(\"id\":\"4829\",\"firstname\":\"Brandy\")}"
    };
    std::string id{ "\"id\":\"" };

    for (auto f = s.find("\"id\":\""); f != s.npos; f = s.find(id, f)) {
        std::istringstream iss{ std::string{ s.begin() + (f += id.length()), s.end() } };
        int id; iss >> id;
        std::cout << id << '\n';
    }
}

Надежный?Ну, просто надеюсь, что никто не называет детей "id":" ...

...