Design, Develop and Implement 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.
CODE IN C Language :-
#include<stdio.h>#include<string.h>
#include<stdlib.h>
char strng[100], pt[100], rp[100];
int start = 0, patfound = 0;
int lasts, lastp, lastr;
void rplcptrn()
{
int i, j;
lastr = strlen(rp)-2;
if(lastp != lastr)
{
printf("\n\tInvalid length of replace string");
exit(0);
}
else
{
i = start;
for(j=0; j<=lastr; j++)
{
strng[i] = rp[j];
i++;
}
}
return;
}
void fdptrn()
{
int i, j, inmatch;
lasts = (strlen(strng))-2;
lastp = (strlen(pt))-2;
int endmatch;
for(endmatch = lastp; endmatch<=lasts; endmatch++, start++)
{
if(strng[endmatch] == pt[lastp])
{
inmatch = start;
j=0;
while(j<lastp)
{
if(strng[inmatch] == pt[j])
{
inmatch++;
j++;
}
else
{
break;
}
}
if(j == lastp)
{
patfound = 1;
rplcptrn();
}
}
}
return;
}
void main()
{
printf("\n\tEnter the main string(STR): ");
fgets(strng, 100, stdin);
printf("\n\tEnter the pattern to be matched(PAT): ");
fgets(pt, 100, stdin);
printf("\n\tEnter the string to be replaced(REP): ");
fgets(rp, 100, stdin);
printf("\n\tThe string before pattern match is : \n\t\t\t\t\t %s", strng);
fdptrn();
if(patfound == 0)
printf("\n\tThe pattern is not found in the main string");
else
printf("\n\tThe string after pattern match and replace is : \n\t\t\t\t\t %s",strng);
return;
}
Comments
Post a Comment