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:
- char c = 'a';
- if(c.equals('a') || c.equals('e') || c.equals('i') || c.equals('o') || c.equals('u'))
- {
- // c is a vowel
- }
However, you can solve this with a single condition:
- char c = 'a';
- if(vowels.contains(c))
- {
- // c is a vowel
- }
This technique is really useful when you need to classify a string. For example:
- if (arithmetics.contains(operator))
- {
- ...
- }
- else if (logical.contains(operator))
- {
- ...
- }
- else if (comparisons.contains(operator))
- {
- ...
- }
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.
Enviado por miguelSantirso hace over 2 years — modificado por última vez hace less than a minute