Are there any library functions in for counting the number of a particular character in a string std::string ?

3 answers 3

There are of course.

The name is obvious - std :: count :

 // count algorithm example #include <iostream> // std::cout #include <algorithm> // std::count #include <vector> // std::vector int main () { int myints[] = {10,20,30,30,20,10,10,20}; // 8 elements int mycount = std::count (myints, myints+8, 10); std::cout << "10 appears " << mycount << " times.\n"; // 锌芯写褋褔械褌 褔懈褋谢邪 褝谢械屑械薪褌芯胁: std::vector<int> myvector (myints, myints+8); mycount = std::count (myvector.begin(), myvector.end(), 20); std::cout << "20 appears " << mycount << " times.\n"; return 0; } 
  • Funny - I didn鈥檛 even remember, I started to remember the functions in string ... - Harry
  • and it works faster than samopisnaya? - pavel
  • one
    @pavel despite what samopinny. But certainly not slower, because the algorithm is trivial. - 伪位蔚蠂慰位蠀蟿
 #include <iostream> #include <algorithm> int main(void){ std::string s = "aaabla-blaaa"; std::cout << std::count(s.begin(), s.end(), 'a') << std::endl; return 0; } 

    There is in the algorithm function template std :: count_if

    • one
      count_if for predicate counting. By value, just count . - 伪位蔚蠂慰位蠀蟿