简体   繁体   中英

Retrieving substring using string::reverse_iterator

A substring denoted by two std::string::reverse_iterators, how can I copy them out and assign to a new string with normal sequence, not reversely?

One senario may be: A string of "Hello world-John", probe from tail and meet '-' using:

      std::string::reverse_iterator rIter
         = std::find(str.rbegin(), str.rend(), isDelimiterFunc);

And the rIter is pointing at '-'. I want to get the "John" out, but if I do:

  std::string out(str.rbegin(), rIter - 1);

I will got "nhoj".

Thanks guys!

You might want to use string::rfind to solve that problem.

std::string f;
auto pos = f.rfind("-");
std::string f2= f.substr(pos);

Otherwise you can obtain the underlying iterator of a reverse_iterator through the base() member function and it returns an off-by-one iterator.

As requested...

Following the lead of @pmr's answer which provides a simpler approach, to search for one of multiple characters in std::string you can use std::string::find_last_of() :

std::string str("Hello world-John");
const size_t idx = str.find_last_of("-x!@~");
if (std::string::npos != idx)
{
    std::cout << str.substr(idx+1) << "\n";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM