Question

I want my program to replace every vowel in the inputted string.

public static void main(String[] args) {
        // TODO code application logic here
         char vowel;
        vowel = 'a'+'e'+'i'+'o'+'u';

          Scanner keyboard = new Scanner (System.in);
          System.out.print("Enter your name: ");
          String name = keyboard.nextLine();
          name = name.replace( vowel,'*');   
          System.out.print(name);

It just returns the string as normal but i want the vowels to be *'s.

Était-ce utile?

La solution

Change

name = name.replace( vowel,'*');

To

name = name.replaceAll("[aeiouAEIOU]","*");

Autres conseils

name = name.replaceAll("(?i)[aeiou]", "*")

When you do:

vowel = 'a'+'e'+'i'+'o'+'u';

You get a character equal to the values of those chars added up. Characters in java are stored as numbers. Instead, do String.replace on each vowel.

Replace:

name = name.replace( vowel,'*');  

With:

name = name.replaceAll("[aeiou]",'*');

Firstly, this:

char vowel;
vowel = 'a'+'e'+'i'+'o'+'u';

is not at all what you want. You're essentially performing regular addition here, treating chars as integers.

Now to get to your question: you can use replaceAll for this, but you also use a simple loop:

char[] rawName = keyboard.nextLine().toCharArray();

for (int i = 0; i < rawName.length; i++) {
    if ("aeiou".indexOf(rawName[i]) >= 0) {
        rawName[i] = '*';
    }
}

String name = String.valueOf(rawName);
name=name.replaceall("[aeiou]","*'s");
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top