C++ Program to find substring in a given string [DEVCPP/GCC]


STRING FUNCTION: FIND

size_t  find  (const string& substring , size_t  pos=0 )

This function is used to search a string for a given substring specified in its arguments. If the substring is found, it returns the starting index of the substring else returns -1. The argument pos specifies the position from which the search will begin. The default value of pos is 0.

PROGRAM

// Program to find substring in a given string

#include <iostream>
#include <string>

using namespace std;

int main()
{
        string str,sub;
        int pos;

        cout<<"ENTER STRING: ";
        getline(cin,str);

        cout<<"ENTER SUBSTRING: ";
        cin>>sub;

        pos=str.find(sub,0);

         if(pos==-1)
        {
               cout<<"SUBSTRING NOT FOUND !";
        }
        else
        {
               cout<<"SUBSTRING FOUND AT POSITION: "<<pos;
        }

         return 0;
}

OUTPUT

C++ Program to find substring in a given string with output

Share this

Related Posts

FIND US ON FACEBOOK!