How to remove vowels from a string in Java
In this example, we are going to remove/eliminate all the vowels from a string in Java. In our alphabets we have five vowels i.e. a,e,i,o,u/A,E,I,O,U. Sometimes you need to remove all the vowels from your string or sometime this question may be raised in the interview.
To remove the vowels from the string we are going to use replaceAll()
method of String
class.
replaceAll() method :
public String replaceAll(String regex, String replacement)
Replaces each substring of this string that matches the given regular expression with the given replacement.
Throws: PatternSyntaxException – if the regular expression’s syntax is invalid
EliminateVowel.java
package org.websparrow;
import java.util.Scanner;
public class EliminateVowel {
public static void main(String[] args) {
String str = "";
System.out.print("New string: " + eliminateVowelMethod(str));
}
public static String eliminateVowelMethod(String string) {
try {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the string: ");
string = scanner.nextLine();
return string.replaceAll("[aeiouAEIOU]", "");
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
Output:
Enter the string: Hello I am a String.
New string: Hll m Strng.