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

标签 c++ qt qt5 qstring

假设我有一个包含以下内容的 QString:

"#### some random text ### other info
a line break ## something else"

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


回答

多亏了答案,解决方案非常简单,在文档中被忽略了 使用 count() 方法,您可以将要计数的内容作为参数传递。

最佳答案

你可以使用 this方法并传递 # 字符:

#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;
}

然后以 gcc 为例,您可以使用以下命令或类似的命令来查看结果。

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

输出将是:9

如您所见,您无需遍历自己,因为 Qt 便捷方法已经使用内部 qt_string_count. 为您完成了该工作

关于c++ - 如何计算 QString Qt 中的特定字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18547369/

相关文章:

c++ - OpenGL 三角形旋转

c++ - 在执行时在布局中添加自定义小部件

c++ - 在 C++ 中设置单个位

c++ - 在 2D、z 顺序渲染系统中组合点(粒子)和三角形( Sprite )

C++ 在 { Token 之前无效使用不完整类型或预期初始化程序

c++ - Qt C++ 在按键时播放声音 - 几秒钟后停止工作

linux - 如何将系统输出重定向到我的 gui 应用程序(qt、linux)?

macos - 错误 : Could not resolve SDK path for 'macosx10.9'

c++ - QSharedPointer 在 emit 中被销毁

php - nginx 不转发 POST 到 @fallback