C program to remove the vowels from a string

Write a C program to remove the vowels from a string :

In this example, we will learn how to remove all the vowels from a string using ‘c’ program. Let’s take a look into the program first :

C Program :

#include <stdio.h>
#include <stdlib.h>

//7
int isVowel(char c)
{
    switch (c)
    {
    case 'a':
    case 'e':
    case 'i':
    case 'o':
    case 'u':
    case 'A':
    case 'E':
    case 'I':
    case 'O':
    case 'U':
        return 1;
    default:
        return 0;
    }
}

int main()
{
    //1
    char *str;

    //2
    int i = 0;
    int j = 0;

    //3
    str = malloc(sizeof(char) * 256);

    //4
    printf("Enter a string : ");
    scanf("%[^\n]s", str);

    //5
    for (i = 0; str[i] != '\0'; i++)
    {
        //6
        if (isVowel(str[i]) == 0)
        {
            //8
            str[j] = str[i];
            j++;
        }
    }

    //9
    str[j] = '\0';

    //10
    printf("%s\n", str);
}

Explanation :

The commented numbers above denote the below steps.

  1. Create one char pointer variable ‘str’ to save the string.
  2. Create two int variables i and j.
  3. Allocate memory to the variable str.
  4. Take the input from the user and save it in str variable.
  5. Run one for loop and check each character. Variable i is used for the current variable index.
  6. Check if the current character is vowel or not.
  7. int isVowel(char c) is used to check if a character is vowel or not. If yes return 1. Else return 0.
  8. If it is not a vowel, take the character of index i and place it in the position of index j and increment the value of j. If the character is vowel, we are not incrementing the value of j.
  9. After the loop is completed, assign ‘\0’ to the index j.
  10. Finally, print out the result.

Sample Output :

Enter a string : Hello World!!
Hll Wrld!!

Enter a string : abcdefghijklmnopqrstuvwxyz
bcdfghjklmnpqrstvwxyz

Enter a string : One word
n wrd

Enter a string : aeiou