计算搜索词出现的次数

问题描述 投票:0回答:1

我希望计算 Qt 中 QPlainTextEdit 中给定搜索词的出现次数。

我尝试过使用 while (find()) 来遍历所有出现的情况,但对于任何较大的文档来说,性能都很糟糕,并且每次尝试执行搜索时都会将程序锁定几秒钟。

int PlainTextSearch::countOccurrences(QString term)
{
    int occurrences = 0;

    QTextCursor searchCursor = textEdit->textCursor();
    searchCursor.movePosition(QTextCursor::Start);
    textEdit->setTextCursor(searchCursor);
   
    // Moves the searchCursor to the term
    // True for as long as the term is found
    while(textEdit->find(term)) {
        ++occurrences;
    }
}

除了使用 find() 之外,我找不到任何其他方法来执行此操作,这似乎是性能瓶颈所在。

有更好的方法吗?

c++ qt search
1个回答
1
投票

您正在寻找的是 QString::count() 函数。

这是基于您的代码的解决方案(我还没有编译它,它可能包含拼写错误):

int PlainTextSearch::countOccurrences(const QString& term)
{
    return textEdit->toPlainText().count(term);
}

我还没有测量它的性能,但我怀疑它会比你的解决方案更快。

© www.soinside.com 2019 - 2024. All rights reserved.