11

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.

Vincent Duprez
  • 3,772
  • 8
  • 36
  • 76

2 Answers2

13

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.

Random Citizen
  • 1,272
  • 3
  • 14
  • 28
László Papp
  • 51,870
  • 39
  • 111
  • 135
  • This is indeed right, I just don't see the difference between myString.count(QLatin1Char('#')) and myString.count("#") – Vincent Duprez Aug 31 '13 at 12:49
  • 1
    With .count("#") you automatically convert your utf-8 string into latin1. With .count(QLatin1Char('#') you do it explicitly. Does not sound like a big difference, but your version won't work anymore when in your .pro file the QT_NO_CAST_TO_ASCII variable is set. Why would anyone do this? Better control over your encoding. With automatic utf-8 -> latin1 conversion there can come some nasty and hard to find bugs into your program. – Greenflow Aug 31 '13 at 15:53
3

Seems QString has useful counting methods.

https://doc.qt.io/qt-6/qstring.html#count-2

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;
Violet Giraffe
  • 32,368
  • 48
  • 194
  • 335
Vittorio Romeo
  • 90,666
  • 33
  • 258
  • 416
  • @Vincent: I think it is not the right solution because this iterator is convoluted, and also the count-2 link provided is not the one needed in here. See my full working code below. – László Papp Aug 31 '13 at 12:42