In this tutorial we will see how to remove vowels from String in java.
Table of Contents
Using replaceAll() method
We will use String’s replaceAll()
method to remove vowels from String.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
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<Character> 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
vowelsSet
and add all vowels to it. - Iterate over String
str
and check ifvowelsSet
does not contain the character. - If
vowelsSet
does 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.
Was this post helpful?
Let us know if this post was helpful. Feedbacks are monitored on daily basis. Please do provide feedback as that\'s the only way to improve.