2

I am new to c++ and would like to know how to extract multiple substrings, from a single string, in between the same delimiters?

ex.

"{("id":"4219","firstname":"Paul"),("id":"4349","firstname":"Joe"),("id":"4829","firstname":"Brandy")}"

I want the ids:

4219 , 4349 , 4829

mrflash818
  • 930
  • 13
  • 24

2 Answers2

2

You can use regex to match the ids:

#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() << ',';
    }

}

See it live on Coliru

Not a real meerkat
  • 5,604
  • 1
  • 24
  • 55
1

Well, here is the q&d hack:

#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';
    }
}

Reliable? Well, just hope nobody names children "id":" ...

Swordfish
  • 12,971
  • 3
  • 21
  • 43