如何计算QString Qt中的特定字符

Vin*_*rez 8 c++ qstring qt qt5

想象一下,我有一个包含这个的QString:

"#### some random text ### other info
a line break ## something else"
Run Code Online (Sandbox Code Playgroud)

我怎样才能知道我的QString中有多少哈希?换句话说,如何从这个字符串中获取数字9?


回答

感谢答案,解决方案非常简单,忽略了在使用count()方法的文档中,您可以传递您正在计算的参数.

lpa*_*app 12

您可以使用方法并传递#角色:

#include <QString>
#include <QDebug>

int main()
{
    // Replace the QStringLiteral macro with QLatin1String if you are using Qt 4.

    QString myString = QStringLiteral("#### some random text ### other info\n \
                                       a line break ## something else");
    qDebug() << myString.count(QLatin1Char('#'));
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

然后使用gcc,您可以使用以下命令或类似的内容来查看结果.

g ++ -I/usr/include/qt -I/usr/include/qt/QtCore -lQt5Core -fPIC main109.cpp && ./a.out

输出将是: 9

正如您所看到的,没有必要自己迭代,因为Qt便捷方法已经为您使用内部功能qt_string_count.