public class ReplaceVowels {
public static void main(String args[]) throws IOException {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the String:");
String str = bf.readLine();
char[] c = new char[str.length()];
for (int i = 0; i < str.length(); i++) {
if (c[i] == 'a' || c[i] == 'e' || c[i] == 'i' || c[i] == 'o'
|| c[i] == 'u') {
System.out.println(str.replace(c[i], '?'));
}
}
}
}
why does the str.replace
method not work? What should I do to make it work?
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]", "?" );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With