1

我想获得搜索的所有“索引”。显然“QStringList::indexOf”一次返回一个索引......所以我必须做一个while循环。但它也“仅”进行完全匹配。

如果我想返回所有拥有“husky”的项目索引怎么办......然后可能是“dog”......然后是“dog 2”。我是否坚持比“QString::contains”然后循环来完成这个?还是我缺少更多与“QStringList 类”相关的方式

QStringList dogPound;
dogPound    << "husky dog 1"
            << "husky dog 2"
            << "husky dog 2 spotted"
            << "lab dog 2 spotted";
4

2 回答 2

2

你可以使用QStringList::filter方法。它返回一个新QStringList的,其中包含从过滤器传递的所有项目。

QStringList dogPound;
dogPound    << "husky dog 1"
            << "husky dog 2"
            << "husky dog 2 spotted"
            << "lab dog 2 spotted";

QStringList spotted = dogPound.filter("spotted");
// spotted now contains "husky dog 2 spotted" and "lab dog 2 spotted"
于 2013-08-06T14:26:42.760 回答
1

这似乎是在 QStringList 中查找特定 QString 位置的最直接的方法:

#include <algorithm>

#include <QDebug>
#include <QString>
#include <QStringList>


int main(int argc, char *argv[])
{
    QStringList words;
    words.append("bar");
    words.append("baz");
    words.append("fnord");

    QStringList search;
    search.append("fnord");
    search.append("bar");
    search.append("baz");
    search.append("bripiep");

    foreach(const QString &word, search)
    {
        int i = -1;
        QStringList::iterator it = std::find(words.begin(), words.end(), word);
        if (it != words.end())
            i = it - words.begin();

        qDebug() << "index of" << word << "in" << words << "is" << i;
    }

    return 0;
}
于 2015-02-22T20:28:24.760 回答