This C program performs string pattern matching and replacement. It takes in a main string, pattern string, and replacement string from the user. It then calls a find_and_replace function which searches for the pattern in the main string and replaces all occurrences with the replacement string. If the pattern is not found, a message is printed. The replaced main string is then printed.
This C program performs string pattern matching and replacement. It takes in a main string, pattern string, and replacement string from the user. It then calls a find_and_replace function which searches for the pattern in the main string and replaces all occurrences with the replacement string. If the pattern is not found, a message is printed. The replaced main string is then printed.
/*2. 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.*/ // ************************************************************************ #include<stdlib.h> #include<stdio.h> char str[100], pat[100], rep[100], temp[100]; void read_string() { printf("Enter the Main String\n"); gets(str); printf("Enter the Pattern String\n"); gets(pat); printf("Enter the Replace String\n"); gets(rep); } void find_and_replace() /* Function for searching and replace a string */ { int i, si=0, pi=0, ci, ti=0, ri=0, flag=0, pos=0; while (str[si] != '\0') { pi = 0; ci = si; /* Compare for one same char of str[] with pat[] */ while (str[ci] == pat[pi] && pat[pi] != '\0') { /*Then find pattern is matching completely*/ ci++; pi++; si++; } if(pat[pi] == '\0') { pos = ci; while(rep[ri]!='\0') { temp[ti]=rep[ri]; ri++; ti++; } ri=0; flag=1; } else { temp[ti]=str[pos]; pos++; si++; ti++; } } temp[ti] = '\0'; for(i=0; temp[i]!='\0'; i++) { str[i]=temp[i]; } str[i]='\0'; if(flag==0) { printf("Pattern was not found\n"); exit(0); } } int main() { read_string(); printf("The Main String is: %s\n", str); printf("The Pattern String is: %s\n", pat); printf("The Replace String is: %s\n", rep); find_and_replace(); printf("The Replaced Main String is: %s\n", str); return 0; }