This blog is under construction

Monday 15 July 2013

C program to delete a character from a string

Write a C program to remove a character from the given string.


  #include <stdio.h>
  #include <string.h>

  int main() {
        char input[256], output[256];
        int i = 0, j = 0, ch;

        /* get the input string from the user */
        printf("Enter your input string:");
        fgets(input, 256, stdin);
        input[strlen(input) - 1] = '\0';

        /* get the input character from user */
        printf("Enter your input character:");
        ch = getchar();

        /* delete the input character from input string */
        while (input[i] != '\0') {
                /* copy all characters other than i/p char */
                if (input[i] != ch) {
                        output[j++] = input[i];
                }
                i++;
        }

        output[j] = '\0';

        /* copy the contents of output array to input array */
        strcpy(input, output);

        /* print the result */
        printf("After deleting %c from the given string:\n", ch);
        printf("%s\n", input);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter your input string:Gonna delete e from me
  Enter your input character:e
  After deleting e from the given string:
  Gonna dlt  from m


No comments:

Post a Comment