You are here

C program to delete vowels from a string

C program to remove or delete vowels from a string: if input string is "C programming," then the output will be "C prgrmmng." In the program, we create a new string and process input string character by character, and if a vowel is found it is excluded in the new string, otherwise the character is added to new string after the string ends we copy the new string into the original string. Finally, we obtain a string without vowels.

C programming code

  1. #include <stdio.h>
  2. #include <string.h>
  3.  
  4. int check_vowel(char);
  5.  
  6. int main()
  7. {
  8.   char s[100], t[100];
  9.   int c, d = 0;
  10.  
  11.   printf("Enter a string to delete vowels\n");
  12.   gets(s);
  13.  
  14.   for(c = 0; s[c] != '\0'; c++) {
  15.     if(check_vowel(s[c]) == 0) {       // If not a vowel
  16.       t[d] = s[c];
  17.       d++;
  18.     }
  19.   }
  20.  
  21.   t[d] = '\0';
  22.  
  23.   strcpy(s, t);  // We are changing initial string. This is optional.
  24.  
  25.   printf("String after deleting vowels: %s\n", s);
  26.  
  27.   return 0;
  28. }
  29.  
  30. int check_vowel(char ch)
  31. {
  32.     if (ch == 'a' || ch == 'A' || ch == 'e' || ch == 'E' || ch == 'i' || ch == 'I' || ch =='o' || ch=='O' || ch == 'u' || ch == 'U')
  33.       return 1;
  34.     else
  35.       return 0;
  36. }

Output of program:
C program to delete vowels from a string output

C programming code using pointers

  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. #include<string.h>
  4.  
  5. int check_vowel(char);
  6.  
  7. main()
  8. {
  9.    char string[100], *temp, *pointer, ch, *start;
  10.  
  11.    printf("Enter a string\n");
  12.    gets(string);
  13.  
  14.    temp = string;
  15.    pointer = (char*)malloc(100);
  16.  
  17.   if( pointer == NULL )
  18.    {
  19.       printf("Unable to allocate memory.\n");
  20.       exit(EXIT_FAILURE);
  21.    }
  22.  
  23.    start = pointer;
  24.  
  25.    while(*temp)
  26.    {
  27.       ch = *temp;
  28.  
  29.       if ( !check_vowel(ch) )
  30.       {
  31.          *pointer = ch;
  32.          pointer++;
  33.       }
  34.       temp++;
  35.    }
  36.    *pointer = '\0';
  37.  
  38.    pointer = start;
  39.    strcpy(string, pointer); /* If you wish to convert original string */
  40.    free(pointer);
  41.  
  42.    printf("String after removing vowel(s): \"%s\"\n", string);
  43.  
  44.    return 0;
  45. }
  46.  
  47. int check_vowel(char a)
  48. {
  49.   if (a == 'a' || a == 'e' || a == 'i' || a == 'o' || a == 'u')
  50.     return 1;
  51.   else if (a == 'A' || a == 'E' || a == 'I' || a == 'O' || a == 'U')
  52.     return 1;
  53.   else
  54.     return 0;
  55. }