Write a C function that defines two strings as parameters, as follows, and checks whether the second string (str2) is a substring of the first one (str1).

Posted by Tushar Bedekar



int substring_finder(char* str1, char* str2);
The function should return an integer as follows:
• 2 if str2 is a substring of str1 and also of same length
o e.g. str1 = "Hello" and str2= "Hello"
• 1 if str2 is a substring of str1 and of different lengths
o e.g. str1 = "Hello World" and str2= "Hello"
• 0 if str2 is not a substring of str1
o e.g. str1 = "Hello" and str2= "Helo"


 

program me starts from here:-

#include(string.h)                                         //  note place '<' & '>' in place of '(' & ')'
#include(stdio.h)
int substring_finder(char *,char *);
int main()
{
  char *str1,*str2;
  int fl;
  clrscr();
  printf("Enter the main string:");
  gets(str1);
  printf("Enter the sub-string:");
  gets(str2);
  fl=substring_finder(str1,str2);

  if(fl==0)
    printf("\n'str2' is not a substring of 'str1'");
  else if(fl==1)
    printf("\n'str2' is a substring of 'str1'");
  else if(fl==2)
    printf("\nBoth are equal");

getch();
return 0;
}
int substring_finder(char *str,char *sub)
{
  int flag;
  if(strcmp(str,sub)==0)
     flag=2;
  else if(strstr(str,sub))
     flag=1;
  else
     flag=0;

  return flag;
}

0 comments:

Post a comment

back to top