Comparing a char with multiple characters

2020-04-01 08:53发布

问题:

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?

回答1:

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



回答2:

One more for the clever regex department:

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


回答3:

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:

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:

One more for Java 8:

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


回答6:

One of the ways to do this in using a List of Character and in java9 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++;
    }
}