检查 Java 中字符串的每个字符的较短条件代码

Shorter condition code of checking each character of a string in Java

这是我的代码,用于检查字符串中的每个字符是否为元音字母

if(word.charAt(i) == 'a' || word.charAt(i) == 'e' || word.charAt(i) == 'i' || word.charAt(i) == 'o' 
                    || word.charAt(i) == 'u')

我必须为 Java 中的每个元音重复 word.charAt(i) 吗?我在代码中重复了 5 次。在形成我的逻辑条件时,是否有更短的方法或者我是否受制于重复代码?

我想到的一个简短的布尔测试类似于

"aeiou".contains(Character.toString(word.charAt(i)))

做一个函数,随处使用。

   public function isVowel(String word, int index){
    return "aeiou".contains(Character.toString(word.charAt(i)));
   }

称其为

 isVowel(word,i);
String vowel ="aeiou";

if(vowel.contains(word.charAt(i)+"" ) )
{

}

您甚至不应该访问单个字符:

if( word.matches( "^[aeiou]+$" ) ){
    // all vowels
}
if( word.matches( ".*[aeiou].*" ) ){
    // one vowel
}

int count = word.length() - word.replaceAll("[aeiou]", "").length();
// or
int count = word.replaceAll("[^aeiou]", "").length();

您可以使用 "aeiou".indexOf(word.charAt(i)) < 0 但性能可能不如您的好,因为创建了一个新字符串并对其进行了查找过程。我不确定 :D