joefuldoe
joefuldoe

Reputation: 65

Search part of a QString in QStringList in Qt

In QString, contains() method works like this:

QString s = "long word";
s.contains("long"); // -> True

I would assume that QStringList works similarly, but it does not:

QStringList s;
s << "long word";
s << "longer word";
s.contains("long"); // -> False

QStringList contains searches for the exact match, which does not work like I want it to. Is there an easy way to find a part of a string in a QStringList? I could of course loop through the QStringList and use contains() there, but is there a better way?

Upvotes: 6

Views: 12800

Answers (1)

IAmInPLS
IAmInPLS

Reputation: 4125

You can use the function QStringList::filter() :

QStringList QStringList::filter(const QString &str, Qt::CaseSensitivity cs = Qt::CaseSensitive) const

Returns a list of all the strings containing the substring str.

and check that the list returned is not empty.

In your case:

QStringList s;
s << "long word";
s << "longer word";
s.filter("long"); // returns "long word", and also "longer word" since "longer" contains "long"

Upvotes: 7

Related Questions