Compare One String with Multiple Values in One Expression

Compare one String with multiple values in one expression

I found the better solution. This can be achieved through RegEx:

if (str.matches("val1|val2|val3")) {
// remaining code
}

For case insensitive matching:

if (str.matches("(?i)val1|val2|val3")) {
// remaining code
}

How to Compare a String to Two Other Strings All in the Same Line Using .equals()

You can't use equals to compare with two strings unless you call it twice, like this:

String input = kb.next().toLowerCase(); 
boolean hit = input.equals("y") || input.equals("yes");

You could alternatively use a regex:

boolean hit = input.matches("y(es)?");

Or if you don't mind matching the string "ye" as well as "y" and "yes", you could use startsWith:

boolean hit = "yes".startsWith(input);

String.equals() with multiple conditions (and one action on result)

Possibilities:

  • Use String.equals():

    if (some_string.equals("john") ||
    some_string.equals("mary") ||
    some_string.equals("peter"))
    {
    }
  • Use a regular expression:

    if (some_string.matches("john|mary|peter"))
    {
    }
  • Store a list of strings to be matched against in a Collection and search the collection:

    Set<String> names = new HashSet<String>();
    names.add("john");
    names.add("mary");
    names.add("peter");

    if (names.contains(some_string))
    {
    }

C# - Compare one string variables to multiple other string (String.Equals)

Create collection of values:

string[] values = { "de", "de-DE" };

Use Contains method:

if (values.Contains(interSubDir))

It gives O(n) performance.

If your collection is very big, then you can use Array.BinarySearch method, that gives you O(log n) performance.

if (Array.BinarySearch(values, interSubDir) >= 0)

However, the collection must be sorted first.

Array.Sort(values);

What's the prettiest way to compare one value against multiple values?

Don't try to be too sneaky, especially when it needlessly affects performance.
If you really have a whole heap of comparisons to do, just format it nicely.

if (foobar === foo ||
foobar === bar ||
foobar === baz ||
foobar === pew) {
//do something
}

How can I compare a string to multiple correct values in Bash?

Instead of saying:

if [ "$cms" != "wordpress" && "$cms" != "meganto" && "$cms" != "typo3" ]; then

say:

if [[ "$cms" != "wordpress" && "$cms" != "meganto" && "$cms" != "typo3" ]]; then

You might also want to refer to Conditional Constructs.



Related Topics



Leave a reply



Submit