Duglas
Duglas

Reputation: 251

How to split a string on a range?

I'd like to know how to split a string on a range:

std::string = "some<foo>some<bar>some...";

Need to get a range between <...>:

foo
bar

Upvotes: 1

Views: 199

Answers (2)

WayHunter
WayHunter

Reputation: 1225

Using iterator:

string str = "some<foo>some<bar>some";

string::iterator i = str.begin(), token = i;

while (i != str.end()) {
    if(*i == '<') {
        token = i+1;
    }
    else if (*i == '>') {
        string item(token, i);
        cout << item << endl;
    }
    i++;
}

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726579

You can use string::find repeatedly:

size_t pos = 0;
while (true) {
    size_t strt = mystring.find('<', pos);
    pos = mystring.find('>', strt+1);
    if (strt == string::npos || pos == string::npos) break;
    cout << mystring.substr(strt+1, pos-strt-1) << endl;
}

Upvotes: 2

Related Questions