Compare single QString against many, evaluate to true if it matches any
-
If I wanted to compare 1 string against any string in a list at once, what could I do besides QStringList::contains()?
Logically, there's always the ability to test the strings one at a time, but Qt's extensive conveniences for strings makes me think there has to be a "better" (more convenient) way.Looking for something like this:
if(str1 == QString(str2 || str3 || str4))
Could be inclusive or (|
), comma, etc.. I just don't know what to look for. -
Hi,
What kind of string are you using for the comparison ?
How long can that list be ? -
QString. Ideally, the list could be as long as I want, i.e. a variadic static method or something
-
What I meant is the content of the string not the object type :-)
-
@SGaist I suppose they would all have to be the same length for the comparison to work properly.
-
If I wanted to compare 1 string against any string in a list at once, what could I do besides QStringList::contains()?
Logically, there's always the ability to test the strings one at a time, but Qt's extensive conveniences for strings makes me think there has to be a "better" (more convenient) way.Looking for something like this:
if(str1 == QString(str2 || str3 || str4))
Could be inclusive or (|
), comma, etc.. I just don't know what to look for.@Ewan-Green said in Compare single QString against many, evaluate to true if it matches any:
if(str1 == QString(str2 || str3 || str4))
With this intention/syntax, makes me think of regular expression (use
QRegularExpression
):(str2|str3|str4)
. I guess it's one way of reducing typing a bit. This is only for literals, as per your code, unless you meant variables, butQString(str2 || str3 || str4)
does not imply that to me. -
If it's an exact match you are looking for then QStringList::indexOf looks like what you want.
If you want it search whether there's an occurrence of your string within an entry of the list then using this overload with a simple regexp should do the trick.
And no there's no need for the strings to be all the same length.
-
if using a static or pre-loaded list of strings then create a map and compare your input string against the map keys using map::find(). Your search times will generally be much shorter. the general mechanism here is to use a binary search of a sorted list to determine if your input string is found.