将char与多个字符进行比较

时间:2014-07-27 03:59:08

标签: java arrays if-statement char boolean

for(int j=0 ; j<str.length() ; j++) {
    if(char[j]==(a||e||i||o||u))
        count++;
}

我知道(a||e||i||o||u)的结果是布尔值,因此无法比较,但我们如何检查多个角色的存在?

6 个答案:

答案 0 :(得分:30)

这不是你想要的。请使用堆栈switch声明:

for(int j = 0; j < str.length(); j++)
     switch(str.charAt(j)) {
         case 'a':
         case 'e':
         case 'i':
         case 'o':
         case 'u':
             count++;
     }

或者,因为我是正则表达式爱好者,所以这是一种使用正则表达式的方法! :)

Matcher matcher = Pattern.compile("[aeiou]").matcher(str);
while(matcher.find())
    count++;

稍后修复此代码时出现错误,thanks to user2980077

答案 1 :(得分:4)

聪明的正则表达部门还有一个:

count = str.replaceAll("[^aeiou]","").length();

答案 2 :(得分:2)

如果您使用这些类,可以尝试使用regex或简单的String

String s = "aeiouaeiou";//string to count
int count = 0;
for (int i = 0; i < s.length(); i++) {

  //One method
  if ("aeiou".indexOf( s.charAt(i) ) >= 0) {
    count++;
  }

  //Another one
  if (Character.toString( s.charAt(i) ).matches("[aeiou]")) {
    count++;
  }

}

答案 3 :(得分:0)

如果我真的需要使用char[]数组而不是String实例,我总是使用Character类和正则表达式。如果你不知道正则表达式是什么,你应该学习它们,因为它们在处理字符串时非常有用。此外,您可以在Regexr练习。

对于你的例子,我会用它:

char[] data = "programming in Java is fun".toCharArray();
int counter = 0;

for(int i = 0; i<data.length; i++){
    if(Character.toString(data[i]).matches("[aeiou]")){
        counter++;
    }
}

System.out.println(counter); // writes: 8

if语句的作用基本上是它使包含当前字符的新String实例能够使用String类中的方法。方法boolean matches(String regex)检查您的字符串是否满足regex参数给出的条件。

答案 4 :(得分:0)

Java 8还有一个:

count = str.chars()
           .filter(c -> c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' )
           .count();

答案 5 :(得分:0)

使用List Character时,其中一种方法可能是:

List<Character> vowels = List.of('a','e','i','o','u'); // pverloaded convenience factory method 
for(int j=0 ; j < str.length() ; j++) {
    if(vowels.contains(char[j])) {
        count++;
    }
}