This is a C Program to search a word & replace it with the specified word.
This C Program Searches a Word & Replace it with the Specified Word.
Take input from the user and performs string operations as shown in the program below.
Here is source code of the C Program to find the possible subsets of the String. The C program is successfully compiled and run on a Linux system. The program output is also shown below.
/* * C Program to Search a Word & Replace it with the Specified Word */ #include <stdio.h> #include <string.h> #include <stdlib.h> /*Function to replace a string with another string*/ char *rep_str(const char *s, const char *old, const char *new1) { char *ret; int i, count = 0; int newlen = strlen(new1); int oldlen = strlen(old); for (i = 0; s[i] != '\0'; i++) { if (strstr(&s[i], old) == &s[i]) { count++; i += oldlen - 1; } } ret = (char *)malloc(i + count * (newlen - oldlen)); if (ret == NULL) exit(EXIT_FAILURE); i = 0; while (*s) { if (strstr(s, old) == s) //compare the substring with the newstring { strcpy(&ret[i], new1); i += newlen; //adding newlength to the new string s += oldlen;//adding the same old length the old string } else ret[i++] = *s++; } ret[i] = '\0'; return ret; } int main(void) { char mystr[100], c[10], d[10]; printf("Enter a string along with characters to be rep_strd:\n"); gets(mystr); printf("Enter the character to be rep_strd:\n"); scanf(" %s",c); printf("Enter the new character:\n"); scanf(" %s",d); char *newstr = NULL; puts(mystr); newstr = rep_str(mystr, c,d); printf("%s\n", newstr); free(newstr); return 0; }
In this C Program, we are reading a string along with characters to be replaced using ‘mystr’. The rep_str() function is used to replace a string with another string. If condition statement is used to compare the length of the new and old string values are equal.
Using ret variable allocate memory. If that memory is NULL then it will exit the function. If else condition statement, is used to compare the value of substring with the newstring. If the condition is true, then execute the statement by copying the new string to the ret[] variable.
Add the value of newlength to the new string and also add the same old length to the old string. Otherwise, if the condition is false, then execute the else condition statement assign the value of ‘s’ variable to ‘ret[]’ variable. Print the replaced word using printf statement.
$ cc string31.c $ a.out Enter a string along with characters to be rep_strd: prrrogram C prrrogramming Enter the character to be rep_strd: rr Enter the new character: mmm prrrogram C prrrogramming pmmmrogram C pmmmrogramming
Sanfoundry Global Education & Learning Series – 1000 C Programs.
Here’s the list of Best Books in C Programming, Data-Structures and Algorithms
- Practice BCA MCQs
- Watch Advanced C Programming Videos
- Practice Computer Science MCQs
- Apply for C Internship
- Check Computer Science Books