Remove all vowels in a string with Java

后端 未结 5 966
不思量自难忘°
不思量自难忘° 2021-01-19 12:46

I am doing a homework assignment for my Computer Science course. The task is to get a users input, remove all of the vowels, and then print the new statement.

I kno

5条回答
  •  情书的邮戳
    2021-01-19 13:06

    I don't think your instructor wanted you to call Character.isLetter('a') because it's always true.

    The simplest way of building the result without regexp is using a StringBuilder and a switch statement, like this:

    String s = "quick brown fox jumps over the lazy dog";
    StringBuffer res = new StringBuffer();
    for (char c : s.toCharArray()) {
        switch(c) {
            case 'a': // Fall through
            case 'u': // Fall through
            case 'o': // Fall through
            case 'i': // Fall through
            case 'e': break; // Do nothing
            default: // Do something
        }
    }
    s = res.toString();
    System.out.println(s);
    

    You can also replace this with an equivalent if, like this:

    if (c!='a' && c!='u' && c!='o' && c!='i' && c!='e') {
        // Do something
    }
    

提交回复
热议问题