Count character occurrences in a string in C++

Count character occurrences in a string in C++

#include <algorithm>

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

Pseudocode:

count = 0
For each character c in string s
  Check if c equals _
    If yes, increase count

EDIT: C++ example code:

int count_underscores(string s) {
  int count = 0;

  for (int i = 0; i < s.size(); i++)
    if (s[i] == _) count++;

  return count;
}

Note that this is code to use together with std::string, if youre using char*, replace s.size() with strlen(s).

Also note: I can understand you want something as small as possible, but Id suggest you to use this solution instead. As you see you can use a function to encapsulate the code for you so you wont have to write out the for loop everytime, but can just use count_underscores(my_string_) in the rest of your code. Using advanced C++ algorithms is certainly possible here, but I think its overkill.

Count character occurrences in a string in C++

Old-fashioned solution with appropriately named variables. This gives the code some spirit.

#include <cstdio>
int _(char*__){int ___=0;while(*__)___=_==*__++?___+1:___;return ___;}int main(){char*__=_la_blba_bla__bla___;printf(The string %s contains %d _ charactersn,__,_(__));}

Edit: about 8 years later, looking at this answer Im ashamed I did this (even though I justified it to myself as a snarky poke at a low-effort question). This is toxic and not OK. Im not removing the post; Im adding this apology to help shifting the atmosphere on StackOverflow. So OP: I apologize and I hope you got your homework right despite my trolling and that answers like mine did not discourage you from participating on the site.

Leave a Reply

Your email address will not be published. Required fields are marked *