Remove the vowels from a string in Java
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 Java.
Method 1: Using a Loop
This method iterates through the string and constructs a new string without vowels.
public class RemoveVowels { public static String removeVowels(String str) { String result = ""; for (char c : str.toCharArray()) { if ("aeiouAEIOU".indexOf(c) == -1) { result += c; } } return result; } public static void main(String[] args) { String str = "Hello World"; System.out.println("String without vowels: " + removeVowels(str)); } }
Output: String without vowels: Hll Wrld
Method 2: Using Recursion
This method removes vowels recursively.
public class RemoveVowelsRecursive { public static String removeVowelsRecursive(String str) { if (str.isEmpty()) return ""; char first = str.charAt(0); String rest = removeVowelsRecursive(str.substring(1)); return ("aeiouAEIOU".indexOf(first) == -1) ? first + rest : rest; } public static void main(String[] args) { String str = "Programming"; System.out.println("String without vowels: " + removeVowelsRecursive(str)); } }
Output: String without vowels: Prgrmmng
Method 3: Using StringBuilder
This method uses StringBuilder to remove vowels efficiently.
public class RemoveVowelsStringBuilder { public static String removeVowels(String str) { StringBuilder result = new StringBuilder(); for (char c : str.toCharArray()) { if ("aeiouAEIOU".indexOf(c) == -1) { result.append(c); } } return result.toString(); } public static void main(String[] args) { String str = "Count Vowels"; System.out.println("String without vowels: " + removeVowels(str)); } }
Output: String without vowels: Cnt Vwls