Java Program to Replace First Occurrence Vowel with ‘-‘ in a String

In this tutorial, We will learn writing java program to Replace First vowel that occurs in the input string with ‘-‘. For any input string, we have to find vowels which occurs very first in the string and print the character after replacing that vowels with ‘-‘.

For example

Case1: If the user enters the string ‘Python is fun’

The output should be ‘Pyth-n is fun’, as the character ‘o’, is first vowel occurs in the string so it is replaced by ‘-‘.

Case2: If the user enters the string ‘Engineer’

The output should be ‘-ngineer’, as the character ‘E’, is first vowel occurs in the string so it is replaced by ‘-‘.

Java Program to Replace First Occurrence of Vowels with ‘-‘ in a String

import java.util.*;
public class Main
{
    public static void main (String[]args)
    {
        int max_count = 0;
        char max_char=Character.MIN_VALUE;
        ArrayList<Character> arr = new ArrayList<Character>(Arrays.asList('a','e','i','o','u','A','E','I','O','U'));
        System.out.println("Java program to Replace first Vowel With '-' ");
        Scanner sc = new Scanner (System.in);
        System.out.println ("Please enter a String");
        String str = sc.nextLine(); 
        StringBuilder tempStr = new StringBuilder(str);
        for(int i = 0; i < str.length(); i++){
            if(arr.contains(str.charAt(i))) {        
                    tempStr.setCharAt(i, '-');
                    break;
            }    
        }
        System.out.println ("String after replacing first vowel");
        System.out.println (tempStr);
    }
}

Output

Java program to Replace first Vowel With '-' 
Please enter a String
Quescol
String after replacing first vowel
Q-escol

Explanation

As the input from the user is ‘Quescol’, the output obtained is ‘Q-escol’, the for’ loop will iterate with each element of the string and checks for the vowels once it found the first vowel, it replaces the vowel with ‘-‘ and terminates the loop by storing the characters into tempStr variable which is returned as the output.