This blog is under construction

Wednesday 17 July 2013

C program to remove the given character from a string

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


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

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

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

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

        /* remove the input character from input string */
        while (ipStr[i] != '\0') {
                if (ipStr[i] == ch) {
                        i++;
                        continue;
                }

                /* store characters other than character to remove */
                opStr[j++] =ipStr[i];
                i++;
        }

        opStr[j] = '\0';

        strcpy(ipStr, opStr);

        /* print the result */
        printf("\nAfter Removing %c from the input String:\n", ch);
        printf("Resultant String: %s\n", ipStr);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter your input string:Helloworld
  Enter the character to remove:l

  After Removing l from the input String:
  Resultant String: Heoword



No comments:

Post a Comment