This blog is under construction

Monday 24 June 2013

C program to replace a substring with another string

Write a C program to replace a portion of string by another string.


  #include <stdio.h>
  #include <string.h>
  int main() {
        char str[256], substr[128], replace[128], output[256];
        int i = 0, j = 0, flag = 0, start = 0;

        /* get the input string from the user */
        printf("Enter your input string:\n");
        fgets(str, 256, stdin);

        /* get the substring to be removed */
        printf("Enter the string to be removed:\n");
        fgets(substr, 128, stdin);

        /* get the substring to be added */
        printf("Enter the string to replace:\n");
        fgets(replace, 128, stdin);
        str[strlen(str) - 1] = '\0';
        substr[strlen(substr) - 1] = '\0';
        replace[strlen(replace) - 1] =  '\0';

        /* check whether the substring to be replaced is present */
        while (str[i] != '\0') {
                if (str[i] == substr[j]) {
                        if (!flag)
                                start = i;
                        j++;
                        if (substr[j] == '\0')
                                break;
                        flag = 1;
                } else {
                        flag = start = j = 0;
                }
                i++;
        }

        if (substr[j] == '\0' && flag) {
                for (i = 0; i < start; i++)
                        output[i] = str[i];
                /* replace substring with another string */
                for (j = 0; j < strlen(replace); j++) {
                        output[i] = replace[j];
                        i++;
                }

                /* copy remaining portion of the input string "str" */
                for (j = start + strlen(substr); j < strlen(str); j++) {
                        output[i] = str[j];
                        i++;
                }

                /* print the output string */
                output[i] = '\0';
                printf("Output: %s\n", output);
        } else {
                printf("%s is not a substring of %s\n", substr, str);
        }
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter your input string:
  Hello Mr Roy  
  Enter the string to be removed:
  Mr
  Enter the string to replace:
  Mister 
  Output: Hello Mister Roy



No comments:

Post a Comment