在 QString 中,contains() 方法是这样工作的:
QString s = "long word";
s.contains("long"); // -> True
我假设 QStringList 的工作方式类似,但事实并非如此:
QStringList s;
s << "long word";
s << "longer word";
s.contains("long"); // -> False
QStringList 包含对精确匹配的搜索,这并不像我希望的那样工作。有没有一种简单的方法可以在 QStringList 中找到字符串的一部分?我当然可以循环遍历 QStringList 并在那里使用 contains(),但是有更好的方法吗?
最佳答案
您可以使用函数 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.
并检查返回的列表是否为空。
在你的情况下:
QStringList s;
s << "long word";
s << "longer word";
s.filter("long"); // returns "long word", and also "longer word" since "longer" contains "long"
关于c++ - 在 Qt 的 QStringList 中搜索 QString 的一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37548344/