0

For example I have a string:

int random_int = 123; // let's pretend this integer could have various values!!

std::string str = "part1 Hello : part2 " + std::to_string(random_int) + " : part3 World ";

All parts are divided by the characters :

Let's say I want to find a substring from "part2" to the next character :, which would return part2 123 in this case.

I know how to find the pos of "part2" by str.find("part2"), but I don't know how to determine the length to the next : from that "part2", because the length can be of various length.

For example, I know that part3 substring could be extracted with str.substr(str.find("part3"));, but only because it's at the end...

So, is there a subtle way to get the substring part2 123 from that string?

3
  • 4
    std::string::find takes a position find in the string should start at as the second argument, so it seems you can find the first : and then do str.find(':', previous_delimeter_position + 1)
    – fas
    Commented Apr 18, 2020 at 16:23
  • @fas Ah, this points me towards the right direction, but will that also work if the input is scattered like std::string str = "part2 123 : part3 World : part1 Hello " and I still want to return "part2 123" with the same code piece?
    – MrWhiteee
    Commented Apr 18, 2020 at 16:37
  • 1
    std::istringstream coupled with std::getline makes an easy general purpose tokenizer. Commented Apr 18, 2020 at 16:43

0

Browse other questions tagged or ask your own question.