Count character occurrences in a string in C++

Viewed 403589

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

14 Answers

Using the lambda function to check the character is "_" then the only count will be incremented else not a valid character

std::string s = "a_b_c";
size_t count = std::count_if( s.begin(), s.end(), []( char c ){return c =='_';});
std::cout << "The count of numbers: " << count << std::endl;

The range based for loop comes in handy

int count = 0;
string line = "bla_bla_blabla_bla";

for (char c: line)
   if (c == '_') count++;

I would have done something like that :)

const char* str = "bla_bla_blabla_bla";
char* p = str;    
unsigned int count = 0;
while (*p != '\0')
    if (*p++ == '_')
        count++;
Related