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
Call a Method of Subclass in Java
Java Executors: How to Set Task Priority
How to Read Xml Response from a Url in Java
Javabean Wrapping with Javafx Properties
Jsoup Character Encoding Issue
Wrap the String After a Number of Characters Word-Wise in Java
Java - Generate Random Range of Specific Numbers Without Duplication of Those Numbers - How To
Run Command Prompt as Administrator
Java: Join Array of Primitives with Separator
How to Do a Soap Web Service Call from Java Class
Get Yesterday's Date Using Date