Comparing a char with multiple characters

2020-04-01 08:04发布

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

I know the result of (a||e||i||o||u) is a Boolean so can't compare but how can we check for multiple character presence?

6条回答
姐就是有狂的资本
2楼-- · 2020-04-01 08:36

This is not doing what you want. Please use a stack switch statement:

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

Or, since I'm a regex enthusiast, here's an approach using regular expressions! :)

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

There was a mistake in this code fixed later on, thanks to user2980077

查看更多
爷的心禁止访问
3楼-- · 2020-04-01 08:42

If you use the classes you can try with regex or simple 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++;
  }

}
查看更多
该账号已被封号
4楼-- · 2020-04-01 08:43

If I really need to work with a char[] array and not with a String instance, I always use the Character class and regular expressions. If you don't know what regular expressions are you should learn them because they are very useful when working with strings. Also, you can practice at Regexr.

For your example I'd use this:

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

What the if statement does is basically it makes a new String instance containing the current character just to be able to use the methods from the String class. The method boolean matches(String regex) checks whether your string satisfies the conditions given with the regex argument.

查看更多
混吃等死
5楼-- · 2020-04-01 08:45

One more for Java 8:

count = str.chars()
           .filter(c -> c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' )
           .count();
查看更多
Rolldiameter
6楼-- · 2020-04-01 08:49

One of the ways to do this in using a List of Character and in could be :

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++;
    }
}
查看更多
对你真心纯属浪费
7楼-- · 2020-04-01 08:59

One more for the clever regex department:

count = str.replaceAll("[^aeiou]","").length();
查看更多
登录 后发表回答