How to count a specific character in QString Qt

Imagine I have a QString containing this:

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

How to find out how many hashes in my QString? In other words, how can I get the number 9 from this line?


Answer

Thanks to the answers, the solution was quite simple, it was missed that in the documentation using the count () method, you can pass what you consider as an argument.

+6
source share
2 answers

You can 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, for example, using gcc, you can execute 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

The output will be: 9

As you can see, there is no need to repeat through yourself, since the Qt-convenience method already does this for you using the internal qt_string_count .

+7
source

QString seems to have useful counting methods.

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

Or you can just iterate over all the characters in the string and increment the 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; 
+1
source

Source: https://habr.com/ru/post/952874/


All Articles