JAVA PROGRAM
Program to remove all vowels from a string |Java Program|
Introduction
When working with strings in Java, there are many scenarios where you might want to manipulate the text. One common operation is the removal of vowels from a string. In this blog post, we will walk through a simple Java program that takes an input string from the user, removes all vowels, and outputs the result.
Understanding the Problem
Vowels in the English language are the letters 'a', 'e', 'i', 'o', 'u' and their uppercase counterparts 'A', 'E', 'I', 'O', 'U'. The goal is to remove all these characters from a given string.
Code
import java.util.Scanner;
public class Vowel {
public static void main(String[] args) {
String str1, str2;
Scanner scan = new Scanner(System.in);
System.out.println("Enter a string:");
str1 = scan.nextLine();
System.out.println("Removing vowels from the string [" + str1 + "]");
// Use replaceAll method to remove vowels
str2 = str1.replaceAll("[aeiouAEIOU]", " ");
System.out.println("All vowels removed...");
System.out.println(str2);
}
}
Output
Enter a string:
college
Removing vowels from the string [college]
All vowels removed...
c ll g
In this example, the input string "college" is processed, and the vowels 'o' and 'e' are replaced by spaces, resulting in "c ll g".
How the Program Works
- Import Scanner Class: The Scanner class is imported to allow us to take input from the user.
- Initialize Variables: Two strings str1 and str2 are declared. str1 will hold the input string, and str2 will hold the string with vowels removed.
- Take User Input: The program prompts the user to enter a string. This input is stored in str1.
- Remove Vowels: The replaceAll method is used on str1 to replace all vowels with a space " ". The regular expression [aeiouAEIOU] is used to match all vowels (both lowercase and uppercase).
- Output the Result: The program prints the original string and the string with vowels removed.
Conclusion
Removing vowels from a string is a common text processing task, and Java makes it straightforward with its powerful string handling capabilities. This simple program demonstrates how to take user input, process the string, and produce the desired output using the replaceAll method.
This basic example can be extended and modified to suit various applications, such as text preprocessing in natural language processing tasks or simple data cleaning operations.
Try modifying the program yourself! For instance, you can alter the code to remove only lowercase vowels, or you can replace vowels with different characters instead of spaces. Happy coding!
Post a Comment
0 Comments