How to use std::string::rfind in C++

In this post, we are going to learn about standard function under the string class which is std::string::rfind this function is used to find the last occurrence of a string. Let’s learn how to use std::string:rfind in C++. If this function is called then if a character is present in the string then it returns the index of that last occurring character else it will return the position of the pointer which is at the end of the string.

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

void findString(string line,string c)
{
    size_t gotThat;

    gotThat=line.rfind(c);

    if(gotThat==string::npos)
    {
        cout<<"char not found in string given!"<<endl;
        
    }
    else
    {
        cout<<"Char fount at position "<<gotThat<<endl;
    }
    

}

int main()
{
    string line("He I got you");
    string ch("I");

    findString(line,ch);
}

In the above code, we have created a function findString() which takes two parameters in that first parameter is a string given from which we have to find the last occurrence of a character. The second parameter is the character that we have to find in the given string.

In the main function, we have declared two string and passed it to finString() and this function then does the work i.e it created a variable name gotThat, and parse strings through rfind method thus if that char is present in the string it saves the last occurrence of that string, thus return the index of char.

 

OUTPUT:

Char fount at position 3

Leave a Reply

Your email address will not be published. Required fields are marked *