Remove All Vowels From A String In C Using Switch Case
Removing vowels from a string is a common string manipulation task in programming. This operation involves iterating through a string and selectively excluding characters that are identified as vowels.
In this article, you will learn how to effectively remove all vowels from a given string in C using a switch case statement, a powerful control flow mechanism.
Problem Statement
Strings in C are character arrays, and directly "removing" a character means shifting all subsequent characters to the left. The challenge is to efficiently identify both uppercase and lowercase vowels within a string and construct a new string (or modify the original in place) that contains only the non-vowel characters. This task requires careful character comparison and array manipulation.
Example
Consider the input string: "Hello World" After removing all vowels (a, e, i, o, u, A, E, I, O, U), the expected output would be: "Hll Wrld"
Background & Knowledge Prerequisites
To understand and implement the solutions, you should be familiar with:
- C String Basics: Understanding that strings are null-terminated character arrays (
char[]). - Loops:
fororwhileloops for iterating through strings. - Conditional Statements:
if-elsefor basic decision-making. - Switch Case: Its syntax and how to use it for multi-way branching.
- Character Functions: Basic functions from
liketolower()for case conversion. - Pointers (Optional but helpful): For in-place string modification.
Use Cases or Case Studies
Removing vowels from a string can be useful in various scenarios:
- Text Processing: Pre-processing text for specific analyses where vowels are irrelevant, such as generating phonetic representations or simplified versions of words.
- Data Obfuscation: Creating simpler, yet recognizable, versions of words or names for privacy or identity masking, where original words need to be difficult to reconstruct but still hint at the original.
- Educational Tools: Developing simple language games or exercises that focus on consonant recognition or word puzzles.
- Basic String Compression: In very specific, rudimentary compression algorithms, removing common letters like vowels might be a starting point, though not generally efficient.
- Nickname Generation: Automating the creation of short, memorable nicknames by stripping less critical letters from full names.
Solution Approaches
There are several ways to remove vowels from a string in C, including using if-else ladders, lookup tables, or regular expressions (if a library is available). However, we will focus on using the switch case statement.
Approach 1: Removing Vowels Using a Switch Case (In-Place)
This approach iterates through the string, uses tolower() to normalize characters, and then employs a switch case to identify and skip vowels, copying only consonants to a new position in the same array.
// Remove Vowels from String using Switch Case
#include <stdio.h> // Required for printf, gets (use fgets for safety)
#include <string.h> // Required for strlen
#include <ctype.h> // Required for tolower
#define MAX_LENGTH 100
int main() {
char str[MAX_LENGTH];
char modifiedStr[MAX_LENGTH]; // Optional: to store in a new string
int i, j = 0;
// Step 1: Prompt user for input string
printf("Enter a string: ");
// Using fgets is safer than gets to prevent buffer overflows
// Read up to MAX_LENGTH-1 characters, store in str, from stdin
fgets(str, MAX_LENGTH, stdin);
// Remove the trailing newline character that fgets might read
str[strcspn(str, "\\n")] = 0;
// Step 2: Iterate through the original string
for (i = 0; str[i] != '\\0'; i++) {
// Step 3: Convert current character to lowercase for case-insensitive check
char currentChar = tolower(str[i]);
// Step 4: Use switch case to check if the character is a vowel
switch (currentChar) {
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
// It's a vowel, do not copy it. Skip to the next character.
break;
default:
// It's a consonant or non-alphabetic character, copy it.
modifiedStr[j] = str[i];
j++; // Increment the write index
break;
}
}
// Step 5: Null-terminate the modified string
modifiedStr[j] = '\\0';
// Step 6: Print the modified string
printf("String after removing vowels: %s\\n", modifiedStr);
return 0;
}
Sample Output:
Enter a string: Programming is FUN
String after removing vowels: Prgrmmng s FN
Stepwise Explanation:
- Include Headers:
stdio.hfor input/output,string.hforstrcspn(to remove newline fromfgets), andctype.hfortolower(). - Declare Arrays: Two character arrays,
strto store the input andmodifiedStrto store the result. An integerjis initialized to0to act as a write index formodifiedStr. - Get Input: The program prompts the user to enter a string using
fgets.strcspnis used to remove the newline character thatfgetsincludes. - Iterate String: A
forloop traverses thestrarray from beginning to end until the null terminator\0is encountered. - Convert to Lowercase: Inside the loop,
tolower(str[i])converts the current characterstr[i]to its lowercase equivalent. This simplifies theswitchstatement by only needing to check lowercase vowel cases. - Switch Case Check:
- The
switchstatement checks thecurrentChar.
- The
currentChar matches any of the case labels ('a', 'e', 'i', 'o', 'u'), it means it's a vowel. No action is taken (the break simply exits the switch), effectively skipping the vowel.currentChar does not match any of the vowel cases (default), it means it's a consonant, a digit, a symbol, or a space. This character is then copied from str[i] to modifiedStr[j], and j is incremented to prepare for the next non-vowel character.- Null-Terminate: After the loop finishes,
modifiedStr[j]is set to\0to ensure the new string is properly null-terminated. - Print Output: Finally, the
modifiedStr(without vowels) is printed to the console.
Conclusion
Using a switch case for removing vowels from a string in C offers a clear and organized way to handle multiple comparison conditions. By converting characters to lowercase, the logic simplifies significantly, making the code more readable and maintainable than a long series of if-else if statements. This method effectively creates a new string that retains only the non-vowel characters, demonstrating fundamental string manipulation techniques in C.
Summary
- Problem: Remove all occurrences of vowels (both upper and lower case) from a given string in C.
- Method: Iterate through the string, convert each character to lowercase, and use a
switchcase to identify and skip vowels. - Implementation: Maintain a separate index for the new string, copying only non-vowel characters.
- Key Function:
tolower()fromis crucial for case-insensitive vowel checking. - Result: A new string containing only consonants and other non-vowel characters, null-terminated.