1

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!

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

5 Comments

thanks for your concern pmr, but I cannot do if the delimter is a char set. Lets focus on using string::reverse_iterator.
@Lyn, yes you can using std::string::find_last_of().
@hmjd, thanks! Was confused with find/rfind. I`ll try it right now,
The member function is called base(), and will surprise everyone by returning an iterator that is off by one. See reverse_iterator::base()
@BoPersson Thanks, i got confused somehow.
2

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";
}

1 Comment

Thanks @hmjd, your help resolved my real problem. After cool down, I found myself still curious about the reverse_iterator way. Ive already upvoted you, if there is no answer, Ill accept you. Hope you will understand... again thanks!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.