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.
- Create one char pointer variable ‘str’ to save the string.
- Create two int variables i and j.
- Allocate memory to the variable str.
- Take the input from the user and save it in str variable.
- Run one for loop and check each character. Variable i is used for the current variable index.
- Check if the current character is vowel or not.
- int isVowel(char c) is used to check if a character is vowel or not. If yes return 1. Else return 0.
- 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.
- After the loop is completed, assign ‘\0’ to the index j.
- 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