911 views

Compare a character against a group of characters in only one condition

Sometimes, you will need to compare a character variable against a group of characters. For example, to check if a character is a vowel. The typical solution would be this:

Java
  1. char c = 'a';
  2. if(c.equals('a') || c.equals('e') || c.equals('i') || c.equals('o') || c.equals('u'))
  3. {
  4.   // c is a vowel
  5. }
  6.  

­

However, you can solve this with a single condition:

Java
  1. String vowels = "aeiou";
  2. char c = 'a';
  3.  
  4. if(vowels.contains(c))
  5. {
  6.   // c is a vowel
  7. }
  8.  

­

This technique is really useful when you need to classify a string. For example:

Java
  1. String operator = "and";
  2.  
  3. String arithmetics = "+-*/";
  4. String logical = "andor";
  5. String comparisons = "><>=<==!=";
  6.  
  7. if (arithmetics.contains(operator))
  8. {
  9.     ...
  10. }
  11. else if (logical.contains(operator))
  12. {
  13.     ...
  14. }
  15. else if (comparisons.contains(operator))
  16. {
  17.     ...
  18. }
  19.  

­

WARNING: This technique works fine if you know that operator is actually a valid operator and you just need to classify it. Otherwise, if operator==ndo for example, the string would be classified as a logical operator and it shouldn't.

Tags: Java strings

Embed: