Java program to remove vowels from String

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

Explaination

  1. Take input String from Scanner str1
  2. Call replaceAll() method on String to replace [aeiouAEIOU] with empty String ""
  3. 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
  1. Create HashSet named vowelsSet and add all vowels to it.
  2. Iterate over String str and check if vowelsSet does not contain the character.
  3. If vowelsSet does not contain the character, then add it to result String resultStr
  4. Once loop is complete, then print the resultStr.

That’s all about Java program to remove vowels from String.

[social_share share_on="facebook,twitter,linkedin,whatsapp"][post_navigator in_same_term="true"]

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.