Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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?

like image 244
keith Avatar asked Aug 04 '12 17:08

keith


1 Answers

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]", "?" );
like image 91
Jamie Avatar answered Oct 21 '22 22:10

Jamie