Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java replace a character in a string

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;
    }
like image 840
TEbogo Avatar asked Jun 17 '26 18:06

TEbogo


2 Answers

public String replaceVowels(final String phrase,final String ch) {
    return phrase.replaceAll("[aeiou]", ch);
}
like image 142
Alex Sveshnikov Avatar answered Jun 20 '26 07:06

Alex Sveshnikov


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 );
like image 38
Marc Avatar answered Jun 20 '26 07:06

Marc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!