How to Remove Vowels from a String in Java

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.

Output

Removing Vowels by Using Loops and Conditional Statement

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.

Output

Removing Vowels by Using Loops and Conditional Statement

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

See Also

3 thoughts on “How to Remove Vowels from a String in Java”

Leave a Comment