Remove the vowels from a string in C
Understanding Vowel Removal
Vowel removal involves deleting all vowels (a, e, i, o, u) from a given string.
We will explore three different methods to remove vowels from a string using C.
Method 1: Using a Loop
This method iterates through the string and constructs a new string without vowels.
#include <stdio.h>
#include <string.h>
void removeVowels(char *str) {
int i, j = 0;
char result[strlen(str) + 1];
for (i = 0; str[i] != '\0'; i++) {
if (strchr("aeiouAEIOU", str[i]) == NULL) {
result[j++] = str[i];
}
}
result[j] = '\0';
printf("String without vowels: %s\n", result);
}
int main() {
char str[100];
printf("Enter a string: ");
gets(str);
removeVowels(str);
return 0;
}
Output: String without vowels: Hll Wrld
Method 2: Using Recursion
This method removes vowels recursively.
#include <stdio.h>
#include <string.h>
void removeVowelsRecursive(char *str, int index) {
if (str[index] == '\0') {
return;
}
if (strchr("aeiouAEIOU", str[index]) != NULL) {
memmove(&str[index], &str[index + 1], strlen(str) - index);
removeVowelsRecursive(str, index);
} else {
removeVowelsRecursive(str, index + 1);
}
}
int main() {
char str[100];
printf("Enter a string: ");
gets(str);
removeVowelsRecursive(str, 0);
printf("String without vowels: %s\n", str);
return 0;
}
Output: String without vowels: Prgrmmng
Method 3: Using Pointers
This method uses pointer manipulation to remove vowels.
#include <stdio.h>
#include <string.h>
void removeVowelsPointer(char *str) {
char *src = str, *dest = str;
while (*src) {
if (strchr("aeiouAEIOU", *src) == NULL) {
*dest++ = *src;
}
src++;
}
*dest = '\0';
printf("String without vowels: %s\n", str);
}
int main() {
char str[100];
printf("Enter a string: ");
gets(str);
removeVowelsPointer(str);
return 0;
}
Output: String without vowels: Cnt Vwls