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.
References
Similar Posts
- iText API- Roman and Greek List Example
- Core Java Interview Questions and Answers Part 4
- Java 8 Stream generate() Method
- Java Stream peek() Method Example
- How to parse XML in Java
- Java- Find all Capital Letters in the String
- How to calculate difference between two dates in Java
- Java- Find the element in the List having maximum value
- Java 8 Stream API allMatch(), anyMatch() and noneMatch() method Example
- Java- Find the index of the two numbers in the array whose sum is equal to a given number