How to Remove Vowels from a String in Java? Strings in Java are sequences of characters that are immutable, meaning that once the string is created it can not be changed. In this article we will guide you through the process of removing vowels from strings in Java, using a simple and understandable Java program. We will use the technique from basic loop iteration to a more advanced method using Java’s built-in function and regular expression.
Removing Vowels by Using Loops and Conditional Statement
The simplest way to remove a vowel from the string is by iterating over its character, Checking if it is a vowel, and if not adding it to a new string.
public class StrMan {
public static String removeVowels(String str){
String vowels = "AEIOUaeiou";
StringBuilder result = new StringBuilder();
for(int i=0;i<str.length();i++){
char ch = str.charAt(i);
if(vowels.indexOf(ch) == -1){
result.append(ch);
}
}
return result.toString();
}
public static void main(String[] args) {
String orignalString = "English";
String stringWithoutvowel = removeVowels(orignalString);
System.out.println(stringWithoutvowel);
}
}
Output
In the above Java Program, we use a StringBuilder
to construct the new String, character by character. The indexOf
method is used to check if the current character is a vowel, by checking if it exists in the string of vowels.
Removing Vowels by Using Regular Expression
Java String class comes with a powerful method that can perform complex operations using regular expression. To remove vowels, we can use the replaceAll method with a regular expression that matches all vowels.
public class StrMan {
public static String removeVowels(String str){
return str.replaceAll("[AEIOUaeiou]", "");
}
public static void main(String[] args) {
String orignalString = "English";
String stringWithoutvowel = removeVowels(orignalString);
System.out.println(stringWithoutvowel);
}
}
Output
The replaceAll method takes two arguments- The first is a regular expression that matches the characters to be replaced (In this case [AEIOUaeiou] matches all the lower case and upper case vowels), and the second one is the String to replace with the (In this case, an empty String, effectively removing vowels).
Happy Coding
3 thoughts on “How to Remove Vowels from a String in Java”