Manuel Buenrostro
Manuel Buenrostro

Reputation: 131

is it possible to check if a char matches a list of possibilities?

For example I know that when checking strings, you can do something like

if (string.matches("a|e|i|o|u|A|E|I|O|U" ) )
{
   // Then do this code.
}

but is there a way to check if a char matches a list of possibilities? or do I have to check one by one, such as

if(char == a || char == e || char == i )

...ect.

Upvotes: 10

Views: 29309

Answers (4)

Marko Topolnik
Marko Topolnik

Reputation: 200148

From the performance standpoint the optimum approach would be this:

private final BitSet matchChars = matchChars();

private BitSet matchChars() {
  final BitSet bs = new BitSet();
  final String matchString = "aeiouAEIOU";
  for (int i = 0; i < matchString.length(); i++)
     bs.set(matchString.charAt(i));
  return bs;
}

public boolean charMatches(char c) { return matchChars.get(c); }

Memory required for the approach is very modest even if you use the whole 16-bit range afforded by the char type: at most 8 KB.

Upvotes: 3

ajb
ajb

Reputation: 31689

Back before we had Unicode, when the character set was only 128 characters (ASCII) or later 256 (ISO 8859-1), we would often just create an array of Booleans and use a lookup on the character code--very fast. You could still do the same (an array of 65536 booleans isn't all that big by today's memory standards), or something like

static boolean[] vowelSet = new boolean[128]; // all initialized to false by default

static {
    vowelSet['A'] = true;
    vowelSet['E'] = true;
    ...
    vowelSet['u'] = true;
}

and then to look up:

boolean isVowel(char ch) {
    return ch < 128 && vowelSet[ch];
}

I think that's still the approach I'd take if efficiency were extremely important. Usually it isn't, so one of the other answers probably gives you more readable code.

Upvotes: 0

Mshnik
Mshnik

Reputation: 7032

You could make a collection of chars that you want to check, and see if the collection contains the char in question. A HashSet is ideal here for O(1) look up time. (not that it matters, because the size is constant.)

private static final HashSet<Character> vowels = new HashSet<Character>();

//Initialize vowels hashSet to contain vowel characters
static{
    vowels.add('a');
    vowels.add('e');
    vowels.add('i');
    vowels.add('o');
    vowels.add('u');
    vowels.add('A');
    vowels.add('E');
    vowels.add('I');
    vowels.add('O');
    vowels.add('U');
}

public static boolean isVowel(Character c){
    return vowels.contains(c);
}

Upvotes: 2

rgettman
rgettman

Reputation: 178253

You can do something similar when looking for a char in a String, by using the indexOf method to search the string.

if ("aeiouAEIOU".indexOf(aChar) != -1)

Upvotes: 24

Related Questions