How to Compare a String Against Multiple Other Strings

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 against multiple other strings


["string1","string2","string3"].include? myString

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);

How to compare multiple strings?

First of all, don't use == for strings. You'll learn why later. You want to compare strings by their contents, not where they are in memory. In rare cases a string of "a" could compare false to another string called "a".

Second, split it up so you are performing boolean logic on the comparison results:

else if(!(question.equals("a") || question.equals("b")) {

How to compare multiple strings inside an if statement?

You cannot compare a variable against multiple values like that in C++. You should be doing:

if (theString == "Seven" || theString == "seven" || theString ==  "7")
{
theInt = 7;
cout << "You chose: " << theInt << endl;
}
else if (theString == "Six" || theString == "six" || theString == "6")
{
theInt = 6;
cout << "You chose: " << theInt << endl;
}

Multiple string comparison with C#

Use Enumerable.Contains<T> which is an extension method on IEnumerable<T>:

var strings = new List<string> { "A", "B", "C" };
string x = // some string
bool contains = strings.Contains(x, StringComparer.OrdinalIgnoreCase);
if(contains) {
// do something
}

Comparing a string to multiple items in Python

If, OTOH, your list of strings is indeed hideously long, use a set:

accepted_strings = {'auth', 'authpriv', 'daemon'}

if facility in accepted_strings:
do_stuff()

Testing for containment in a set is O(1) on average.



Related Topics



Leave a reply



Submit