Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - How to double only Vowels

Tags:

java

I am trying to write code that would double all vowels within a string. So if the string is hello, it would return heelloo. This is what I currently have:

public String doubleVowel(String str)
{
    for(int i = 0; i <= str.length() - 1; i++)
    {
        char vowel = str.charAt(i);
        if(vowel == 'a' || vowel == 'e' || vowel == 'i' || vowel == 'o' || vowel == 'u')
        {

        }
    }
}
like image 624
Bry Avatar asked Nov 29 '22 22:11

Bry


1 Answers

You can use a regular expression with a single call to String.replaceAll(String, String) and your method might be static because you don't need any instance state (also, don't forget upper case vowels). Something like

public static String doubleVowel(String str) {
    return str.replaceAll("([AaEeIiOoUu])", "$1$1");
}

Where $1 matches the first (only) pattern grouping expressed in ().

like image 126
Elliott Frisch Avatar answered Dec 04 '22 13:12

Elliott Frisch