C++ programme for function that will scan a string for the occurrence of a given string for substring

#include<iostream.h>
#include<conio.h>
#include<stdio.h>
char *substr(char *string1,char *string2)
{
               char *cp;
               cp=NULL;
               int n=0;
               while(*string1!='\0')
               {
                              if(*string1==*string2)
                              {
                                             n=1;
                                             cp=string1;
                                             while(*string2!='\0')
                                             {
                                                            if(*string1!=*string2)
                                                            {
                                                                           n=0;
                                                                           cp=NULL;
                                                                           break;
                                                            }
                                                            string1++;
                                                            string2++;
                                             }
                              }
                              string1++;
               }
               return cp;
}
void main()
{
               clrscr();
               char str[50],sub[50];
               char *pos;
               cout<<"\nEnter  a string \n";
               gets(str);
               cout<<"\nEnter a string to searched\n";
               gets(sub);
               pos=substr(str,sub);
               if(*pos)
               {
                              cout<<"\nString found\n";
               }
               else
               {
                              cout<<"\nString not found\n";
               }
               getch();
}

OUTPUT:


Enter  a string                                                                
KARTHIK RAO 88
                                                                               
Enter a string to searched                                                     
RAO                                                                             
                                                                               
String found

No comments:

Post a Comment