Removing vowels (with. Java)
This article looks into the “vowel removal” issue.
As I solve coding test problems, I look back on the problems I solved and look into different solution methods to learn more.
Let’s look at the problem first.
problem
In English, the five letters a, e, i, o, and u are classified into vowels.
Complete the solution function so that when the string my_string is given as a parameter, it returns a string with the vowels removed.
Restrictions
- my_string consists of lowercase letters and spaces.
- 1 ≤ length of my_string ≤ 1,000
Input/Output Example
my_string | result |
---|---|
“bus” | “bs” |
“nice to meet you” | “nc t mt y” |
My solution to the problem
class Solution {
public String solution(String my_string) {
StringBuilder answer = new StringBuilder();
char[] arrString = my_string.toCharArray();
for(char charString : arrString){
if(charString != 'a' && charString != 'e' && charString != 'i' && charString != 'o' && charString != 'u'){
answer.append(charString);
}
}
return answer.toString();
}
}
Solution explanation
solution(String my_string): Extracts and returns characters excluding vowels from the given string my_string.
Use StringBuilder to process strings efficiently.
Convert the string to an array of characters, check for each character if it is a collection, and if not, add it to the StringBuilder.
Finally, we convert the StringBuilder to a string and return the result.
Code Advantages
- Efficient string processing: String processing is performed efficiently using StringBuilder.
- Concise implementation: Provides a concise implementation through vowel checking for each character.
Code Disadvantages
- Hard-coded vowel list: When checking vowels, ‘a’, ‘e’, ‘i’, ‘o’, and ‘u’ are hard-coded, so if the vowel changes later, the code must be modified.