Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count a particular character in QString Qt

Tags:

c++

qt

qstring

qt5

Imagine I have a QString containing this:

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

How would I find out how many hashes are in my QString? In other words how can I get the number 9 out of this string?


answer

Thanks to the answers, Solution was quite simple, overlooked that in the documentation using the count() method, you can pass as argument what you're counting.

like image 586
Vincent Duprez Avatar asked Aug 31 '13 10:08

Vincent Duprez


2 Answers

You could use this method and pass the # character:

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

Then with gcc for instance, you can the following command or something similar to see the result.

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

Output will be: 9

As you can see, there is no need for iterating through yourself as the Qt convenience method already does that for you using the internal qt_string_count.

like image 89
lpapp Avatar answered Oct 08 '22 22:10

lpapp


Seems QString has useful counting methods.

http://qt-project.org/doc/qt-5.0/qtcore/qstring.html#count-3

Or you could just loop over every character in the string and increment a variable when you find #.

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;
like image 40
Vittorio Romeo Avatar answered Oct 08 '22 20:10

Vittorio Romeo