Hi there!

I'd like to check if a string is preceeded by another one.
More precisely in this example i would like to check if there is "lion" right before "sleeps".
Im using rfind() to search backwards but for some reason it starts the search from the
beginning of the line and not from "pos" as i liked to that it does.
Should i use another search function maybe?
Thanks in advance!

#include <string>
#include <iostream>
using namespace std;

int main () {
  string str = "The lion aaaaaaa sleeps tonight";
  string str2 = "lion";
  string str3 = "sleeps";
  string::size_type loc = 0;
  string::size_type pos = 0;

  if (( pos = str.find(str3, pos)) != string::npos)
  {
     cout<<"str3 is at position:   "<< pos <<endl;
  }
  loc = str.rfind ( str2.c_str(), pos);

  if (loc != string::npos)
  {
    cout << "Match found at position: " << loc << endl;
  }
  else
    cout << "Match not found." << endl;

  system("pause");
  return 0;
}

Recommended Answers

All 4 Replies

> Im using rfind() to search backwards but for some reason it starts the search
> from the beginning of the line and not from "pos" as i liked to rfind does start the search from pos as you expect.
but it returns the position where the matching subsequence begins
if you require the position of the last element of the subsequence, you can get it by

// rfind (like find) accepts a string
  loc = str.rfind ( str2 /*.c_str()*/, pos);
  if (loc != string::npos)
  {
    loc += str2.size() - 1 ;
    cout << "Match found ending at position: " << loc << endl;
  }

Thank you Vijayan!

But i think i didnt express myself well.

What i would like to do is to search only right before "sleeps".
That is to say only the the size of "lion" + "the space before it"
that would be something like: (str2.size()) + 1.

How should i write it in the code?

something like this

// ...
loc = str.rfind ( str2, pos );
if (loc != string::npos)
{
  // check that there is at least one char between the words
  // ie. ( loc + str2.size() ) is less than  pos
  for( string::size_type i = loc + str2.size() ; i<pos ; ++i )
  {
    // check that every char in between is a space 
    // ie. str[i] is a space for every i
  }
  // ...
}
// ...

Thank you so much Vijayan, its been bugging me for a while, you made my day! :)

Actually i didnt check for 'space' as it always should be there between every word, otherwise
the text has a problem.

This is how i did it with your suggestion:

loc = str.rfind ( str2,pos);
  if (loc != string::npos)
  {
    if ( loc < (pos - (str2.size()+ 1))) // loc <(17 - (4+1))
        cout << "Match not found." << endl;
    else
        cout << "Match found at position: " << loc << endl;
   }
   else
       cout << "Match not found." << endl;
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.