Java program to remove vowels from a string

Introduction :

In this Java programming tutorial, we will learn how to remove all vowels from a user input string. We will learn two different ways to solve this problem. The program will first ask the user to enter a string. After that it will remove all the vowels from the string using two different methods and print out the final string.

Java Program :

import java.util.Scanner;

/**
 * Example class
 */
public class ExampleClass {

    //utility method to print a string
    static void print(String value) {
        System.out.println(value);
    }


    public static void main(String[] args) {
        //1
        Scanner scanner = new Scanner(System.in);

        //2
        String userInput;
        print("Enter a line : ");

        userInput = scanner.nextLine();

        //3
        removeVowels(userInput);
        removeVowels2(userInput);
    }

    static void removeVowels(String line) {
        //4
        String resultString = line.replaceAll("[aeiouAEIOU]", "");

        print("Result string : " + resultString);
    }

    static void removeVowels2(String line) {
        //5
        String resultString = "";
        String vowels = "AEIOUaeiou";

        //6
        for (int i = 0; i < line.length(); i++) {
            if (!vowels.contains(String.valueOf(line.charAt(i)))) {
                resultString += line.charAt(i);
            }
        }

        //7
        print("Result string : " + resultString);
    }
}

Explanation :

The commented numbers in the above program denote the step numbers below :

  1. Create one Scanner object to read the user input string.

  2. Read the string and store it in userInput variable.

  3. Remove the vowels from the string using two different methods: removeVowels and removeVowels2.Pass the user input string to these methods as an argument.

  4. For the first method, to remove all the vowels we are using the removeAll function. The first argument [aeiouAEIOU] means if any character is found equal to any of the character of this list, replace it by an empty character.

  5. For the second method, create one variable resultString to hold the final string. Create one more string variable vowels to hold the characters of the vowels.

  6. Start one for loop and check each character of the string. Append each character to resultString if it is not a vowel, i.e. if it is not present in the vowel string.

  7. resultString will hold the final result string. Print it out.

Sample Output :

Enter a line :
This is a dog
Result string : Ths s  dg
Result string : Ths s  dg

Enter a line :
Hello World
Result string : Hll Wrld
Result string : Hll Wrld

Similar tutorials :