How to count recurring characters at the beginning of a QString?

  • A+
Category:Languages

Im dealing with a list of lines, and I need to count the hashes that occur at the beginning.

#  item 1 ## item 1, 1 ## item 1, 2 #  item 2 

and so on.

If each line is a QString, how can I return the number of hashes occurring at the beginning of the string?

QString s("### foo # bar "); int numberOfHashes = s.count("#"); // Answer should be 3, not 4 

Thanks.

 


Here I use the standard algorithm find_if_not to get an iterator to the first character that is not a hash. I then return the distance from the start of the string to that iterator.

int number_of_hashes(QString const& s) {     auto it = std::find_if_not(std::begin(s), std::end(s), [](QChar c){return c == '#';});     return  = std::distance(std::begin(s), it); } 

EDIT: the find_if_not function only takes a unary predicate, not a value, so you have to pass a lambda predicate.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: