Program: How to remove vowels from String in java?

Removing vowels from String in java? 

In this post, We will learn a program to remove the vowels from String in java programming.

Vowel characters: a, e, i, o and u

Given a String, that contains the vowels may be all or few. From the string need to delete all vowels and print the string without vowels.

Program: How to remove vowels from String in java?

Examples:

Input 1: hello, welcome to java-w3schools blog
Output 1: hll, wlcm t jv-w3schls blg

Input 2: You are reading a Java program to delete vowels in a given string
Output 2: Y r rdng  Jv prgrm t dlt vwls n  gvn strng

This can be done Java, Python, C#, C++, etc.

Method 1: Java program to delete vowels in a given string using arraylist contains method.

We will use a for loop to delete all vowels in string. We will maintain all vowels in ArrayList here. Check each character is available in the vowels list. If yes, then replace that character with empty String.

package examples.java.w3schools.string.programs;

import java.util.ArrayList;
import java.util.List;

public class RemoveVowelsExample {

public static void main(String[] args) {

String content = "Hello, Welcome to Java-w3schools blog";
String output = deleteVowels(content);
System.out.println("String after removing vowels: " + output);
}

/**
* Deletes all vowels from the given string.
*
* @param content
* @return
*/
private static String deleteVowels(String content) {

List al = new ArrayList();
// Adding vowels to arraylist.
al.add('a');
al.add('e');
al.add('i');
al.add('o');
al.add('u');

StringBuffer sb = new StringBuffer(content.toLowerCase());
for (int i = 0; i < sb.length(); i++) {
if (al.contains(sb.charAt(i))) {
sb.replace(i, i + 1, "");
i--;
}
}
return sb.toString();
}
}

Output:

The above program prints the following output.

String after removing vowels: hll, wlcm t jv-w3schls blg

Check isEmpty method in java String class.

Method 2: Remove vowels using String ReplaceAll method:

We can improve the above solution using power of Regular Expressions and String class replaceAll method. See the below program that reveals how to use replace all method.


package examples.java.w3schools.string.programs;

public class RemoveVowelsReplaceAll {

public static void main(String[] args) {

String content = "You are reading a Java program to delete vowels in a given string";
String output = removeVowels(content);
System.out.println("ReplaceAll: removing vowels: " + output);
}

/**
* Replaces all vowels with empty string.
*
* @param content
* @return
*/
private static String removeVowels(String content) {
return content.replaceAll("[aeiouAEIOU]", "");
}
}

Output:

This program produces the following output.


ReplaceAll: removing vowels: Y r rdng  Jv prgrm t dlt vwls n  gvn strng


Discussed the two ways to completely taking out the vowel characters from String.


0 Comments