How to replace replace vowels with a special character in Java?

In your code, you’re creating a new array of characters, which is the same length as your string, but you’re not initialising the array with any values.

Instead, try:

char[] c = str.toCharArray();

However, this isn’t the best way of doing what you’re trying to do. You don’t need a character array or an if statement to replace characters in a string:

String str = bf.readLine();
str.replace( 'a', '?' );
str.replace( 'e', '?' );
str.replace( 'i', '?' );
str.replace( 'o', '?' );
str.replace( 'u', '?' );
System.out.println( str );

The replace function will replace any (and all) characters it finds, or it will do nothing if that character doesn’t exist in the string.

You might also want to look into using regular expressions (as pointed out in edwga’s answer), so that you can shorten those 5 function calls into one:

str.replaceAll( "[aeiou]", "?" );

Leave a Comment