Есть ли какие-либо библиотечные функции в с++ для подсчета количества конкретного символа в строке std::string
?
3 ответа
Есть конечно же.
Название - очевидное - 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;
}
-
-
-
1@pavel смотря какая самописная. Но уж точно не медленнее, ибо алгоритм тривиален.– αλεχολυτ ♦2 мая 2016 в 18:45
#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;
}
Есть в algorithm function template std::count_if
-
1