Program 2:
Design,DevelopandImplementaPrograminCforthefollowingoperationsonStrings.
a. ReadamainString(STR),aPatternString(PAT)andaReplaceString(REP)
b. PerformPatternMatchingOperation:FindandReplacealloccurrencesofPATinST
RwithREPifPATexistsin [Link] PAT
doesnotexistinSTR
[Link]'t useBuilt-
infunctions.
#include <stdio.h>
void readString(char str[])
{
char ch;
int i = 0;
while ((ch = getchar()) != '\n' && ch != EOF)
{
str[i++] = ch;
}
str[i] = '\0';
}
// Function to find length of string
int strLength(char str[])
{
int len = 0;
while (str[len] != '\0')
len++;
return len;
}
// Function to perform find & replace
void findAndReplace(char str[], char pat[], char rep[], char ans[])
{
int i = 0, j = 0, k, c, m;
int flag = 0;
int lenStr = strLength(str);
int lenPat = strLength(pat);
while (i < lenStr)
{
// check if pattern matches
m = i;
c = 0;
while (pat[c] != '\0' && str[m] == pat[c])
{
m++;
c++;
}
// full pattern matched
if (c == lenPat)
{
flag = 1;
// copy replacement
for (k = 0; rep[k] != '\0'; k++)
ans[j++] = rep[k];
i = m; // skip matched pattern
}
else
{
ans[j++] = str[i++];
}
}
ans[j] = '\0';
if (flag == 0)
printf("Pattern not found!!!\n");
else
printf("\nThe RESULTANT string is: %s\n", ans);
}
int main()
{
char STR[100], PAT[100], REP[100], ans[200];
printf("\nEnter the MAIN string: \n");
readString(STR);
printf("\nEnter a PATTERN string: \n");
readString(PAT);
printf("\nEnter a REPLACE string: \n");
readString(REP);
findAndReplace(STR, PAT, REP, ans);
return 0;
}
Output:
Enter the MAIN string:
kssem
Enter a PATTERN string:
s
Enter a REPLACE string:
ksit
The RESULTANT string is: kksitksitem
Index page write the program name as :- Program onString Pattern Matching and
Replacement