3

I am writing a method to replace all vowels in a string with a given character, but it does not work for strings with more than one vowel. It works for "heel" but not for "hello". Please help. My code below:

public Boolean isVowel(char ch){

        char ch2 = Character.toLowerCase(ch); 
        char[] vowels = {'a', 'e', 'i', 'o', 'u'};

        for(int i = 0; i < vowels.length; i++){
            if (ch2 == vowels[i]) {
                return true;
            }
        }
            return false;
    }

    public String replaceVowels(String phrase, char ch){
        String newP = "";
        for(int i = 0; i < phrase.length(); i++){  
            char c = phrase.charAt(i);
            Boolean vowel = isVowel(c);

            if(vowel){ 
               newP = phrase.replace(c, ch);
            }
        }

        return newP;
    }

3 Answers 3

6
public String replaceVowels(final String phrase,final String ch) {
    return phrase.replaceAll("[aeiou]", ch);
}
Sign up to request clarification or add additional context in comments.

Comments

2

Here is one way to replace all vowels in a string with an java char. The (?i) is to make it case insensitive. The "" +ch gets a string from the char.

String str = "hEllo";
char ch = 'X';
str = str.replaceAll( "(?i)[aeiou]", "" +ch );

Could also be more explicit with case like:

String str = "hEllo";
char ch = 'X';
str = str.replaceAll( "[aeiouAEIOU]", "" +ch );

Comments

1

Your problem is newP = phrase.replace(c, ch); You are assigning a last value.

String newP = phrase;
        for(int i = 0; i < phrase.length(); i++){
            char c = phrase.charAt(i);
            Boolean vowel = isVowel(c);

            if(vowel){
                newP = newP.replace(c, ch);
            }
        }

Better solution as answered by Alex just add String,

phrase.replaceAll("[aeiou]", ""+ch);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.