假设我有一个包含以下内容的 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/