【发布时间】:2013-08-31 10:57:03
【问题描述】:
想象一下我有一个包含这个的 QString:
"#### some random text ### other info
a line break ## something else"
如何知道我的 QString 中有多少哈希? 换句话说,我怎样才能从这个字符串中得到数字 9?
回答
感谢答案,解决方案非常简单,在文档中忽略了这一点 使用 count() 方法,您可以将所计数的内容作为参数传递。
【问题讨论】:
想象一下我有一个包含这个的 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. 为您完成了这项工作
【讨论】:
似乎 QString 有有用的计数方法。
http://qt-project.org/doc/qt-5.0/qtcore/qstring.html#count-3
或者你可以循环遍历字符串中的每个字符并在找到#时增加一个变量。
unsigned int hCount(0);
for(QString::const_iterator itr(str.begin()); itr != str.end(); ++itr)
if(*itr == '#') ++hCount;
C++11
unsigned int hCount{0}; for(const auto& c : str) if(c == '#') ++hCount;
【讨论】: