Java - How to double only vowels

I am trying to write code that doubles all the vowels inside a string. Therefore, if the string welcomes, it will return heelloo. This is what I have now:

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')
        {

        }
    }
}
+4
source share
3 answers

You can use a regex with a single call String.replaceAll(String, String), and your method may be staticbecause you don't need any state of the instance (also, don't forget the vowels of the vowels). Sort of

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

Where $1corresponds to the first (only) pattern structure expressed in ().

+13
source

You need to create a temporary extra line (builder) and add vowels twice to this local variable, and then return it:

public String doubleVowel(String str)
{
    StringBuilder sb = new StringBuilder();
    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')
        {
           sb.append(vowel); // add it to the string
        }
        sb.append(vowel); // add any character always, vowels have been added already, resulting in double vowels
    }
    return sb.toString();
}
+5

Let me also add to these good answers a solution that does not involve comparing regular expressions or StringBuilders/ long or, so that you can choose the one that best suits your needs.

public String doubleVowel(String str)
{
    String vow = "aeiou";

    for (int i = 0; i < str.length(); i++) {

                if (vow.indexOf(str.charAt(i)) != -1) {

                    str = str.substring(0, i + 1) + str.substring(i++, str.length());
                }

    }

   return str;
}
+4
source

Source: https://habr.com/ru/post/1657202/


All Articles