Let’s learn how to remove all the vowels in a string. We’ll input the string "hello educative"
into our algorithm. After this, our output should be "hll dctv"
.
Vowels are a limited set of characters in the English language. The characters “a”, “e”, “i”, “o”, and “u” are considered vowels.
We’ll use the following algorithm to remove vowels from a string:
Define a set containing all the vowels.
Loop over the given string.
For every character, we’ll check to see if it is present in the set of vowels.
a. If the character is present in the set, we’ll remove the character from the string.
b. If the character is not present in the vowel set, we’ll continue iterating over the string.
import java.util.Arrays;import java.util.HashSet;import java.util.Set;public class Main{public static void main(String[] args) {String text = "hello educative";StringBuilder stringBuilder = new StringBuilder();Set<Character> vowels = new HashSet<>(Arrays.asList('a', 'e', 'i','o','u'));for(char ch: text.toLowerCase().toCharArray()){if(!vowels.contains(ch)) stringBuilder.append(ch);}String textWithoutVowels = stringBuilder.toString();System.out.println("Original Text - " + text);System.out.println("Text without vowels - " + textWithoutVowels);}}
text
.StringBuilder
instance.HashSet
called vowels
that contains all the vowels.text
string using a for
loop. In the loop, we check if the set vowels
contains the current character. If the character is not in the vowels
set, we add it to the StringBuilder
instance. Otherwise, we reject the character.textWithoutVowels
from the StringBuilder
instance.text
string and the textWithoutVowels
string to the console.