Remove Vowels From String In Java Leetcode Solution Program
In this article, you will learn how to efficiently remove all vowels from a given string using various Java programming techniques, providing clear examples and explanations for each approach.
Problem Statement
The task is to take an input string and produce a new string that contains only the consonants from the original string. Vowels (a, e, i, o, u) can be in either lowercase or uppercase, and they should all be removed. This is a common string manipulation challenge encountered in coding interviews and competitive programming.
Example
Let's consider an input string: "Hello World" The expected output after removing vowels would be: "Hll Wrld"
Background & Knowledge Prerequisites
To understand the solutions presented, a basic understanding of the following Java concepts is beneficial:
- String Basics: How strings are immutable, concatenation, and accessing characters.
- Character Manipulation: Using
chartype,Character.toLowerCase()orCharacter.toUpperCase(). - Loops:
forloops for iterating over characters. - Conditional Statements:
if-elsefor checking conditions. -
StringBuilder: Its purpose for efficient string modification. - Regular Expressions: Basic patterns for string matching and replacement.
- Java Streams (Optional): For more modern and functional programming styles in Java 8+.
Use Cases or Case Studies
Removing vowels from a string has several practical applications:
- Data Sanitization: Cleaning user input by removing specific characters before processing or storage.
- Text Processing: Pre-processing text for natural language processing (NLP) tasks, such as stemming or lemmatization, where vowels might not be relevant.
- Obfuscation/Censorship: Simple text transformations for playful purposes or to slightly obscure sensitive information.
- Puzzle Creation: Generating word puzzles or challenges where words need to be transformed based on vowel presence.
- Shortening Identifiers: In some very specific contexts, reducing the length of identifiers by stripping common characters like vowels.
Solution Approaches
Here are three distinct approaches to remove vowels from a string in Java.
Approach 1: Iterating with StringBuilder
This approach involves iterating through each character of the input string. If a character is not a vowel (case-insensitive), it is appended to a StringBuilder.
- One-line summary: Build a new string by appending non-vowel characters from the original string using a
StringBuilder.
// RemoveVowelsStringBuilder
import java.util.Scanner;
// Main class containing the entry point of the program
public class Main {
public static void main(String[] args) {
// Step 1: Initialize a Scanner for user input
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String inputString = scanner.nextLine();
// Step 2: Create a StringBuilder to efficiently build the result string
StringBuilder resultBuilder = new StringBuilder();
// Step 3: Iterate through each character of the input string
for (char c : inputString.toCharArray()) {
// Step 4: Convert the character to lowercase for case-insensitive check
char lowerC = Character.toLowerCase(c);
// Step 5: Check if the character is NOT a vowel
if (!(lowerC == 'a' || lowerC == 'e' || lowerC == 'i' || lowerC == 'o' || lowerC == 'u')) {
resultBuilder.append(c); // Append original character if it's not a vowel
}
}
// Step 6: Convert StringBuilder to String and print the result
String stringWithoutVowels = resultBuilder.toString();
System.out.println("String without vowels: " + stringWithoutVowels);
scanner.close();
}
}
- Sample Output:
Enter a string: Programming is FUN! String without vowels: Prgrmmng s FN!
- Stepwise explanation for clarity:
- A
Scannerreads the input string from the console. - A
StringBuilderis initialized. It's more efficient than concatenatingStringobjects repeatedly becauseStrings are immutable. - The input string is converted into a character array (
toCharArray()) to easily iterate through its characters. - For each character, it's converted to lowercase using
Character.toLowerCase()to ensure a case-insensitive check. - A conditional check determines if the lowercase character is one of the five vowels ('a', 'e', 'i', 'o', 'u').
- If the character is *not* a vowel, it is appended to the
resultBuilderin its original case. - Finally,
resultBuilder.toString()converts theStringBuildercontent back into aString, which is then printed.
Approach 2: Using String.replaceAll() with Regular Expressions
Java's String.replaceAll() method, combined with regular expressions, offers a very concise way to achieve this.
- One-line summary: Use a regular expression pattern to match all occurrences of vowels (case-insensitive) and replace them with an empty string.
// RemoveVowelsRegex
import java.util.Scanner;
// Main class containing the entry point of the program
public class Main {
public static void main(String[] args) {
// Step 1: Initialize a Scanner for user input
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String inputString = scanner.nextLine();
// Step 2: Define the regular expression for vowels (case-insensitive)
// [aeiouAEIOU] matches any single vowel, irrespective of case
// The empty string "" means to replace matched vowels with nothing
String stringWithoutVowels = inputString.replaceAll("[aeiouAEIOU]", "");
// Step 3: Print the result
System.out.println("String without vowels: " + stringWithoutVowels);
scanner.close();
}
}
- Sample Output:
Enter a string: LeetCode Solutions String without vowels: LtCd Slutns
- Stepwise explanation for clarity:
- A
Scannerreads the input string. - The core of this approach is
inputString.replaceAll("[aeiouAEIOU]", "").
-
replaceAll()is aStringmethod that replaces all substrings that match a given regular expression. -
"[aeiouAEIOU]"is the regular expression. The square brackets define a character set. It means "match any single character that is 'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', or 'U'". - The second argument,
"", specifies that any matched vowel should be replaced with an empty string, effectively removing it.
- The resulting string is stored and printed.
Approach 3: Using Java Streams
For modern Java (Java 8 and above), streams provide a functional and often more readable way to process collections, including character streams from strings.
- One-line summary: Convert the string to a stream of characters, filter out vowels, and then collect the remaining characters into a new string.
// RemoveVowelsStreams
import java.util.Scanner;
import java.util.stream.Collectors;
// Main class containing the entry point of the program
public class Main {
public static void main(String[] args) {
// Step 1: Initialize a Scanner for user input
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String inputString = scanner.nextLine();
// Step 2: Convert the string into a stream of characters
String stringWithoutVowels = inputString.chars()
.filter(c -> !"aeiouAEIOU".contains(String.valueOf((char) c))) // Step 3: Filter out vowels
.mapToObj(c -> String.valueOf((char) c)) // Step 4: Map character int to String
.collect(Collectors.joining()); // Step 5: Collect filtered characters into a String
// Step 6: Print the result
System.out.println("String without vowels: " + stringWithoutVowels);
scanner.close();
}
}
- Sample Output:
Enter a string: Java Programming String without vowels: Jv Prgrmmng
- Stepwise explanation for clarity:
- A
Scannerobtains the input string. inputString.chars()returns anIntStreamrepresenting the Unicode code points of the characters in the string..filter(c -> !"aeiouAEIOU".contains(String.valueOf((char) c)))is the filtering step:
-
cis anintrepresenting a character's Unicode value. -
(char) ccasts it back to achar. -
String.valueOf((char) c)converts the character to aStringto use thecontains()method. -
"aeiouAEIOU".contains(...)checks if the character is present in the string of all vowels (case-sensitive). -
!negates the result, so only non-vowels pass through the filter.
.mapToObj(c -> String.valueOf((char) c))converts each filteredint(character code point) back into aStringobject..collect(Collectors.joining())concatenates all the individualStringobjects (representing characters) into a single finalString.- The resulting string is then printed.
Conclusion
Removing vowels from a string is a fundamental string manipulation task in programming. While there are multiple ways to achieve this in Java, each approach offers distinct advantages. The StringBuilder iteration method provides explicit control and is generally very efficient for large strings. Regular expressions with String.replaceAll() offer the most concise solution for simple patterns. For those leveraging modern Java features, streams provide a functional and often elegant way to filter characters.
Summary
- Problem: Remove all lowercase and uppercase vowels (a, e, i, o, u) from an input string.
-
StringBuilderIteration: - Iterate character by character.
- Check if
Character.toLowerCase(c)is a vowel. - Append non-vowels to a
StringBuilder. - Efficient for performance.
-
String.replaceAll()with Regex: - Use
inputString.replaceAll("[aeiouAEIOU]", ""). - Concise and powerful for pattern matching.
- Java Streams:
- Convert string to
IntStreamusingchars(). -
filter()out vowels using acontains()check. -
collect(Collectors.joining())to reconstruct the string. - Functional and modern Java approach.
- Key Consideration: Choose the approach that best balances readability, performance requirements, and compatibility with your project's Java version.