In this tutorial we will see how to remove vowels from String in java.
[toc]
Using replaceAll() method
We will use String’s replaceAll() method to remove vowels from String.
import java.util.Scanner;
public class StringOperator
{
public static void main(String args[])
{
String str1, str2;
Scanner scan = new Scanner(System.in);
System.out.print("Enter a String : ");
str1 = scan.nextLine();
str2 = str1.replaceAll("[aeiouAEIOU]", "");
System.out.print("All Vowels Removed Successfully..!!\nNew String is : ");
System.out.print(str2);
}
}
Output:
Enter a String : Java2Blog
All Vowels Removed Successfully..!!
New String is : Jv2Blg
All Vowels Removed Successfully..!!
New String is : Jv2Blg
Explaination
- Take input String from Scanner str1
- Call
replaceAll()method on String to replace[aeiouAEIOU]with empty String"" - Print the result String
str2.
Using iterative method
Here is the program to remove vowels from String without replace() or replaceAll() method.
package org.arpit.java2blog;
import java.util.HashSet;
import java.util.Set;
public class RemoveVowelsWithoutReplaceAll {
public static void main(String[] args) {
String str = "Java2Blog";
Set vowelsSet = new HashSet<>();
vowelsSet.add('A');
vowelsSet.add('E');
vowelsSet.add('I');
vowelsSet.add('O');
vowelsSet.add('U');
vowelsSet.add('a');
vowelsSet.add('e');
vowelsSet.add('i');
vowelsSet.add('o');
vowelsSet.add('u');
StringBuffer resultStr = new StringBuffer();
char[] charArray = str.toCharArray();
for (Character chr : charArray) {
if (!vowelsSet.contains(chr))
resultStr.append(chr);
}
System.out.println("Original String is : " + str);
System.out.println("String without vowels is : " + resultStr);
}
}
Output:
Original String is : Java2Blog
String without vowels is : Jv2Blg
String without vowels is : Jv2Blg
- Create HashSet named
vowelsSetand add all vowels to it. - Iterate over String
strand check ifvowelsSetdoes not contain the character. - If
vowelsSetdoes not contain the character, then add it to result StringresultStr - Once loop is complete, then print the
resultStr.
That’s all about Java program to remove vowels from String.