Java program to replace vowels with star

By IncludeHelp Last updated : March 14, 2024

Given a string, write a Java program to convert all vowels with star (asterisk).

Using String.replaceAll() Method

You can convert all vowels of a string to stars by using the String.replaceAll() method. This method accepts two parameters old substring and new substring. Write all vowels as an old substring and star character (*) as a new substring.

Java program to convert all vowels with a star using String.replaceAll()

import java.util.*;

public class Main {
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);

    System.out.print("Enter a string: ");
    String str = sc.nextLine();

    String InputString = str;
    //Replace vowels with star
    str = str.replaceAll("[AaEeIiOoUu]", "*");

    System.out.println(InputString);
    System.out.println(str);
  }
}

Output

The output of the above program will is:

Enter a string: Welcome IncludeHelp!
Welcome IncludeHelp!
W*lc*m* *ncl*d*H*lp!

Using Conditional Statement

To convert vowels to strings, iterate over the characters of the string. Use condition to check and replace the vowels with stars.

Java program to convert all vowels with stars using conditional statement

import java.util.*;

public class Main {
  static Scanner sc = new Scanner(System.in);

  public static void main(String[] args) {
    System.out.print("Enter a string: ");
    String str = sc.nextLine();
    String InputString = str;

    for (int i = 0; i < str.length(); i++) {
      char c = str.charAt(i);
      if ((c == 'A') || (c == 'a') || (c == 'E') || (c == 'e') || (c == 'I') || (c == 'i') || (c == 'O') ||
        (c == 'o') || (c == 'U') || (c == 'u')) {
        String front = str.substring(0, i);
        String back = str.substring(i + 1);
        str = front + "*" + back;
      }
    }
    System.out.println(InputString);
    System.out.println(str);
  }

}

Output

The output of the above program will is:

Enter a string: Welcome IncludeHelp!
Welcome IncludeHelp!
W*lc*m* *ncl*d*H*lp!
 
 

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.