mattobob
mattobob

Reputation: 865

C++ substring contained between 2 specific characters

In c++ would like to extract all substrings in a string contained between specific characters, as example:

std::string str = "XPOINT:D#{MON 3};S#{1}"
std::vector<std:string> subsplit = my_needed_magic_function(str,"{}");
std::vector<int>::iterator it = subsplit.begin();
for(;it!=subsplit.end(),it++) std::cout<<*it<<endl;

result of this call should be:

MON 3
1

also using boost if needed.

Upvotes: 0

Views: 73

Answers (1)

Columbo
Columbo

Reputation: 60989

You could try Regex:

#include <iostream>
#include <iterator>
#include <string>
#include <regex>

int main()
{
    std::string s = "XPOINT:D#{MON 3};S#{1}.";

    std::regex word_regex(R"(\{(.*?)\})");
    auto first = std::sregex_iterator(s.begin(), s.end(), word_regex),
         last  = std::sregex_iterator();;

    while (first != last)
        std::cout << first++->str() << ' ';
}

Prints

{MON 3} {1}

Demo.

Upvotes: 1

Related Questions