Count character occurrences in a string in C++

andre de boer picture andre de boer · Oct 5, 2010 · Viewed 304.3k times · Source

How can I count the number of "_" in a string like "bla_bla_blabla_bla"?

Answer

Benoit picture Benoit · Oct 6, 2010
#include <algorithm>

std::string s = "a_b_c";
size_t n = std::count(s.begin(), s.end(), '_');