Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to delete the vowels from a given string using C language?
In C, removing vowels from a string involves iterating through each character and shifting non-vowel characters to form a new string without vowels. This can be accomplished by checking each character against the vowel set and either skipping or keeping it.
Syntax
for(i=0; i<length; i++) {
if(character is not a vowel) {
result[j++] = str[i];
}
}
Method 1: Using Character Shifting
This approach removes vowels by shifting characters within the original string −
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "TutorialsPoint";
int len = strlen(str);
int i, j;
printf("Original String: %s
", str);
for(i = 0; i < len; i++) {
if(str[i] == 'a' || str[i] == 'e' || str[i] == 'i' ||
str[i] == 'o' || str[i] == 'u' || str[i] == 'A' ||
str[i] == 'E' || str[i] == 'I' || str[i] == 'O' ||
str[i] == 'U') {
for(j = i; j < len; j++) {
str[j] = str[j + 1];
}
len--;
i--; /* Check the same position again */
}
}
printf("After removing vowels: %s
", str);
return 0;
}
Original String: TutorialsPoint After removing vowels: TtrlsPnt
Method 2: Using Two-Pointer Approach
This method uses two indices to build the result more efficiently −
#include <stdio.h>
#include <string.h>
int isVowel(char c) {
return (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' ||
c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U');
}
int main() {
char str[] = "Hello World Programming";
int len = strlen(str);
int i, j = 0;
printf("Original String: %s
", str);
for(i = 0; i < len; i++) {
if(!isVowel(str[i])) {
str[j] = str[i];
j++;
}
}
str[j] = '\0'; /* Null terminate the result */
printf("After removing vowels: %s
", str);
return 0;
}
Original String: Hello World Programming After removing vowels: Hll Wrld Prgrmmng
Comparison
| Method | Time Complexity | Space Complexity | Efficiency |
|---|---|---|---|
| Character Shifting | O(n²) | O(1) | Less efficient for large strings |
| Two-Pointer | O(n) | O(1) | More efficient |
Key Points
- The two-pointer approach is more efficient with O(n) time complexity.
- Always null-terminate the result string using
'\0'. - Check both uppercase and lowercase vowels for complete removal.
- The character shifting method requires decrementing the index when a vowel is found.
Conclusion
Removing vowels from a string in C can be done efficiently using the two-pointer approach. This method preserves the original string structure while eliminating all vowel characters in a single pass.
Advertisements
