C Program to remove all vowels from a string
Objective
Write a C program to remove all vowels from a string.
Algorithm / Approach
- Create a helper function
check(char c)containing aswitchstatement that returns 1 if the character is a vowel, and 0 otherwise. - In
main(), loop through the original string. - If
check(a[i]) == 0(meaning it is a consonant or symbol), copy it to a new arrayb[j]and incrementj. - Append the null terminator to
band print it.
main.c
#include<stdio.h>
int check(char);
int main( ) {
char a[100], b[100];
int i, j = 0;
printf("Enter a string : ");
gets(a);
for(i = 0; a[i] != '\0'; i++) {
if(check(a[i]) == 0) {
b[j] = a[i];
j++;
}
}
b[j] = '\0';
printf("String after removing vowels : %s\n", b);
return 0;
}
int check(char c) {
switch(c) {
case 'a':
case 'A':
case 'e':
case 'E':
case 'i':
case 'I':
case 'o':
case 'O':
case 'u':
case 'U':
return 1;
default:
return 0;
}
}
Expected Output
Enter a string : prowess String after removing vowels : prwss
Explanation of the Program
- This program uses a filtering pattern. We walk through the source string, but we only copy characters over to the destination string if they pass our vowel test.
- Notice how the
switchstatement is structured: multiple cases are stacked together withoutbreakstatements. This allows all vowels to "fall through" and execute the exact samereturn 1instruction.
Complexity
Time Complexity
O(n)
Space Complexity
O(n) - Uses a second array to store the filtered result.