How to write a C Program performs a search and replace for a specified target and replacement string. It will prompt for a string to be searched, a target string to be replaced, and then prompt for a replacement string to replace each target occurrence. The program will repeat, asking for three new strings until a NULL string is entered for the string to be searched, ie. the <Enter Key> only being pressed in C Programming Language ?
Solution:
- /*Description: This program performs a search and replace for a specified target and replacement string. It will prompt for a string to be searched, a target string
- to be replaced, and then prompt for a replacement string to replace each target occurrence. The program will repeat, asking for three new strings until
- a NULL string is entered for the string to be searched, ie. the <Enter Key> only being pressed.
- */
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #define MAX_STR 100
- int main(void)
- {
- //Variable declarations
- char document[MAX_STR], target[MAX_STR], replacement[MAX_STR];
- //Welcome user
- printf("This program performs a search and replace for a specified target and\nreplacement string. It will prompt for a string to be searched, a target string\n");
- printf("to be replaced, and then prompt for a replacement string to replace each target\noccurrence. The program will repeat, asking for three new strings until a\n");
- printf("NULL string is entered for the string to be searched, ie. only the <Enter Key>\nis pressed.\n");
- for (;;)
- {
- //Prompt for and scan in user input
- printf("\nPlease enter a string to search: ");
- fgets(document, MAX_STR, stdin);
- //Terminates loop when conditions met
- if ((strlen(document) == 0) || (strlen(document) == 1))
- return 0;
- else
- document[strlen(document) - 1] = '\0';
- //Continue scanning user input
- printf("\nPlease enter the target string to search for: ");
- scanf("%s", &target);
- printf("\nPlease enter the target replacement string: ");
- scanf("%s", &replacement);
- //Get string lengths
- int docL, tarL, repL;
- docL = strlen(document);
- tarL = strlen(target);
- repL = strlen(replacement);
- //Pointer to 1st occurence of target in document
- char *occurence = strstr(document, target);
- //Checks to see if target string occurs in document string
- if (occurence == NULL)
- {
- printf("\nNo match found!\n");
- printf("%s\n", document);
- }
- else //Replace occurence of target in document
- {
- strncpy(occurence, target, tarL);
- puts(document);
- printf("%s\n", document);
- }
- }
- }