在 Qt 中的 QStringList 中搜索 QString 的一部分

joe*_*doe 4 c++ qt

在 QString 中, contains() 方法的工作方式如下:

QString s = "long word";
s.contains("long"); // -> True
Run Code Online (Sandbox Code Playgroud)

我认为 QStringList 的工作方式类似,但它没有:

QStringList s;
s << "long word";
s << "longer word";
s.contains("long"); // -> False
Run Code Online (Sandbox Code Playgroud)

QStringList 包含对完全匹配的搜索,这不像我想要的那样工作。有没有一种简单的方法可以在 QStringList 中查找字符串的一部分?我当然可以遍历 QStringList 并在那里使用 contains() ,但是有更好的方法吗?

IAm*_*PLS 6

您可以使用函数QStringList::filter()

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

返回包含子字符串 str 的所有字符串的列表。

并检查返回的列表是否为空。

在你的情况下:

QStringList s;
s << "long word";
s << "longer word";
s.filter("long"); // returns "long word", and also "longer word" since "longer" contains "long"
Run Code Online (Sandbox Code Playgroud)