BCSL305 Data Structures and Applications Lab
Program 2:
Develop a Program in C for the following operations on Strings. a. Read a main String (STR), a
Pattern String (PAT) and a Replace String (REP) b. Perform Pattern Matching Operation: Find
and Replace all occurrences of PAT in STR with REP if PAT exists in STR. Report suitable
messages in case PAT does not exist in STR Support the program with functions for each of
the above operations. Don't use Built-in functions.
#include<stdio.h>
void main()
{
char STR[100],PAT[100],REP[100],ans[100];
int i,j,c,m,k,flag=0;
printf("\nEnter the MAIN string: \n"); gets(STR);
printf("\nEnter a PATTERN string: \n"); gets(PAT);
printf("\nEnter a REPLACE string: \n"); gets(REP);
i = m = c = j = 0; while ( STR[c] != '\0') {
// Checking for Match
if ( STR[m] == PAT[i]
) { i++; m++;
flag=1;
if ( PAT[i] == '\0')
{
//copy replace string in ans string
for(k=0; REP[k] != '\0';k++,j++)
ans[j] = REP[k];
i=0;
c=m;
}
}
else //mismatch
{
ans[j] = STR[c];
j++; c++;
m = c; i=0;
Dept. of AI & ML SMVITM, Bantakal Page 8
BCSL305 Data Structures and Applications Lab
}
}
if(flag==0)
{
printf("Pattern doesn't found!!!");
}
else
{
ans[j] = '\0';
printf("\nThe RESULTANT string is:%s\n" ,ans);
}
}
Output:
Case 1:
Enter the MAIN string:
Angry Bird
Enter a PATTERN string:
Bird
Enter a REPLACE string:
Animal
The RESULTANT string is:Angry Animal
Case 2:
Enter the MAIN string:
Artifical Intelligence
Enter a PATTERN string:
Mind
Enter a REPLACE string:
Humane
Pattern doesn't found!!!
Dept. of AI & ML SMVITM, Bantakal Page 9