S1-3
Write a program in `C’ Language that accepts two strings S1 and S2 as input. The
program should check
if S2 is a substring of S1 or not. If S2 is a substring of S1, then the program
should output the
starting location and ending location of S2 in S1. If S2 appears more than once
in S1, then the
locations of all instances have to be given.
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
int i=0,j=0,v,c=0,l1,l2;
char s1[50],s2[50];
clrscr();
printf("Enter 2 strings:n");
gets(s1);
gets(s2);
l1=strlen(s1);
l2=strlen(s2);
while(i<=l1)
{
if(j==l2)
{
v=i-l2+1;
c++;
printf("Start of %d occurance=%d end =%dn",c,v,i);
j=0;
}
else if(s1[i]==s2[j])
{
i++;
j++;
}
else
{
i++;
j=0;
}
}
if(c==0)
printf("Not substring");
getch();
}
Page 1

Bcsl 033 data and file structures lab s1-3

  • 1.
    S1-3 Write a programin `C’ Language that accepts two strings S1 and S2 as input. The program should check if S2 is a substring of S1 or not. If S2 is a substring of S1, then the program should output the starting location and ending location of S2 in S1. If S2 appears more than once in S1, then the locations of all instances have to be given. #include<stdio.h> #include<conio.h> #include<string.h> void main() { int i=0,j=0,v,c=0,l1,l2; char s1[50],s2[50]; clrscr(); printf("Enter 2 strings:n"); gets(s1); gets(s2); l1=strlen(s1); l2=strlen(s2); while(i<=l1) { if(j==l2) { v=i-l2+1; c++; printf("Start of %d occurance=%d end =%dn",c,v,i); j=0; } else if(s1[i]==s2[j]) { i++; j++; } else { i++; j=0; } } if(c==0) printf("Not substring"); getch(); } Page 1