Program to check whether the entered string is a substring of the main string or not.

Write a program that takes two input strings S1 and S2 and finds if S2 is a substring of S1 or not. If S2 is a substring of S1, the program should print the index at S1 at which there is a match. If S2 is not a substring of S1, the program should print -1. If S2 appears in S1 multiple times, print the first index in S1 at which the match occurred.

Code:

#include<iostream>
#include<string.h>
using namespace std;
int main()
{
    int a,i;
    int pos;
    char str1[50],str2[50];
    cout<<"Enter the two strings"<<endl;
   cin>>str1>>str2;
 if(strstr(str1,str2))
 {
     char *pt=strstr(str1,str2);
     pos= pt-str1;
     cout<<pos;
 }
 else
 cout<<"-1";
}

Leave a Reply

Your email address will not be published.