Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 344
Manuel Buenrostro Avatar asked Dec 18 '14 21:12

Manuel Buenrostro


2 Answers

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)
like image 164
rgettman Avatar answered Sep 29 '22 10:09

rgettman


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.

like image 41
Marko Topolnik Avatar answered Sep 29 '22 12:09

Marko Topolnik