270

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

0

14 Answers 14

540
#include <algorithm>

std::string s = "a_b_c";
std::string::difference_type n = std::count(s.begin(), s.end(), '_');
6
  • 29
    The third argument is a char type, i.e., single quote, not double quote...
    – Emerson Xu
    Aug 26, 2016 at 2:23
  • 2
    This is the best answer.
    – Konchog
    Feb 11, 2020 at 14:48
  • 2
    Small note, but the return type is typically signed. For some reason std::count returns type iterator_traits<InputIt>::difference_type, which for most standard containers is std::ptrdiff_t, not std::size_t. Apr 15, 2020 at 7:48
  • As @DanielStevens pointed out, the variable holding the return value of std::count should be of type std::string::difference_type for maximum correctness. I submitted a request to edit the answer to write: std::string::difference_type n = std::count(s.begin(), s.end(), '_');
    – FriskySaga
    Oct 16, 2021 at 23:03
  • 4
    This might be a good case to use auto. ;) Oct 18, 2021 at 6:22
40

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 you're using char*, replace s.size() with strlen(s).

Also note: I can understand you want something "as small as possible", but I'd suggest you to use this solution instead. As you see you can use a function to encapsulate the code for you so you won't 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 it's overkill.

5
  • 37
    Surely we can come up with a totally unreadable templated version with lamba functions and a bind2nd() call ? Oct 5, 2010 at 21:33
  • @Martin I was actually thinking of that. Unfortunately my grasp of C++ functional programming is practically non-existent.
    – jdmichal
    Oct 5, 2010 at 21:34
  • 13
    I think calling a web service would be much more fun than lambdas, then the core algorithm isn't just inscrutable, it's stored elsewhere.
    – Ben Voigt
    Oct 5, 2010 at 21:35
  • 1
    This is no homework question. I am new to c++ and don't have enough knowledge of c++ to program this in a advanced manner. Read: as small as possible. I am able to program this in a simple manner with a for loop and so on, but I was looking for an sophisticated solution, something like the solution of Diego. Next time I will give more information for the reason of the question. Oct 6, 2010 at 7:41
  • Also, you'd want to consume contiguous occurrences in case you did not want duplicates. Like for instance, counting how many pieces you'd get after splitting a string by the desired character. Jun 23, 2016 at 1:26
34

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 _ characters\n",__,_(__));}

Edit: about 8 years later, looking at this answer I'm 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. I'm not removing the post; I'm 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.

17
  • 3
    Seriously? A purposefully obfuscated answer is the best you can do and you think it would ever be appropriate here?
    – Roger Pate
    Oct 5, 2010 at 22:02
  • 5
    @Tamas: int(true) is always 1 in C++.
    – Roger Pate
    Oct 5, 2010 at 22:02
  • 7
    a truly old fashioned solution would declare a prototype for sprintf instead of #including a whole header file! Oct 5, 2010 at 22:05
  • 7
    @Tamas: Of course not, but I don't have my fun while "answering" beginners' questions.
    – Roger Pate
    Oct 5, 2010 at 22:08
  • 13
    Love it. Shame it violates the double underscore rule. Oct 5, 2010 at 22:12
16

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;
7
  • 5
    Please add an explanation - try not to post just plain blocks of code alone. Aug 7, 2018 at 4:32
  • 1
    What do you think, that your answer offers, what a previous answer hasn't already covered? Please edit and expand your answer.
    – hellow
    Aug 7, 2018 at 6:40
  • 1
    Thank you for this code snippet, which might provide some limited, immediate help. A proper explanation would greatly improve its long-term value by showing why this is a good solution to the problem, and would make it more useful to future readers with other, similar questions. Please edit your answer to add some explanation, including the assumptions you've made. Aug 7, 2018 at 8:52
  • 3
    as @phuclv suggested, there must be also return false statement size_t count = std::count_if( s.begin(), s.end(), []( char c ){if(c =='_') return true; else return false; }); Jan 26, 2021 at 12:39
  • 3
    You don't need the if statement size_t count = std::count_if( s.begin(), s.end(), []( char c ){ return c == '_'; }); May 17, 2021 at 17:04
15
#include <boost/range/algorithm/count.hpp>

std::string str = "a_b_c";
int cnt = boost::count(str, '_');
9

You name it... Lambda version... :)

using namespace boost::lambda;

std::string s = "a_b_c";
std::cout << std::count_if (s.begin(), s.end(), _1 == '_') << std::endl;

You need several includes... I leave you that as an exercise...

9
  • 10
    Do you really think a newbie is going to understand any of this? Oct 5, 2010 at 21:56
  • 2
    @Josh: It appears to be a spinoff of the childish laughter in some comments.
    – Roger Pate
    Oct 5, 2010 at 22:00
  • 6
    Some of the world's top programmers have spent the last 15years evolving C++ to the point where we can write this - it's not childish! Oct 5, 2010 at 23:08
  • 10
    It is ridiculous to leave out the includes. May 13, 2013 at 11:07
  • 2
    why all the complexity when std::count already does all what is needed ? Jun 22, 2019 at 7:50
8

Count character occurrences in a string is easy:

#include <bits/stdc++.h>
using namespace std;
int main()
{
    string s="Sakib Hossain";
    int cou=count(s.begin(),s.end(),'a');
    cout<<cou;
}
2
  • 5
    -1 This is the same as the existing top answer from six years earlier – what was this meant to add? There is one difference: this answer uses the wrong header file. stdc++.h is specific to GCC, and even with that compiler it's only intended for use in precompiled headers. Jun 24, 2018 at 19:25
  • 8
    Recommended reading: Why should I not #include <bits/stdc++.h>? Oct 24, 2018 at 10:22
4

There are several methods of std::string for searching, but find is probably what you're looking for. If you mean a C-style string, then the equivalent is strchr. However, in either case, you can also use a for loop and check each character—the loop is essentially what these two wrap up.

Once you know how to find the next character given a starting position, you continually advance your search (i.e. use a loop), counting as you go.

4

I would have done it this way :

#include <iostream>
#include <string>
using namespace std;
int main()
{

int count = 0;
string s("Hello_world");

for (int i = 0; i < s.size(); i++) 
    {
       if (s.at(i) == '_')    
           count++;
    }
cout << endl << count;
cin.ignore();
return 0;
}
0
2

You can find out occurrence of '_' in source string by using string functions. find() function takes 2 arguments , first - string whose occurrences we want to find out and second argument takes starting position.While loop is use to find out occurrence till the end of source string.

example:

string str2 = "_";
string strData = "bla_bla_blabla_bla_";

size_t pos = 0,pos2;

while ((pos = strData.find(str2, pos)) < strData.length()) 
{
    printf("\n%d", pos);
    pos += str2.length();
} 
1

The range based for loop comes in handy

int countUnderScores(string str)
{
   int count = 0;

   for (char c: str)
     if (c == '_') count++;
   
   return count;
}
int main()
{
   string str = "bla_bla_blabla_bla";
   int count = countUnderScores(str);
   cout << count << endl;
}
0

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++;
-4

Try

#include <iostream>
 #include <string>
 using namespace std;


int WordOccurrenceCount( std::string const & str, std::string const & word )
{
       int count(0);
       std::string::size_type word_pos( 0 );
       while ( word_pos!=std::string::npos )
       {
               word_pos = str.find(word, word_pos );
               if ( word_pos != std::string::npos )
               {
                       ++count;

         // start next search after this word 
                       word_pos += word.length();
               }
       }

       return count;
}


int main()
{

   string sting1="theeee peeeearl is in theeee riveeeer";
   string word1="e";
   cout<<word1<<" occurs "<<WordOccurrenceCount(sting1,word1)<<" times in ["<<sting1 <<"] \n\n";

   return 0;
}
-9
public static void main(String[] args) {
        char[] array = "aabsbdcbdgratsbdbcfdgs".toCharArray();
        char[][] countArr = new char[array.length][2];
        int lastIndex = 0;
        for (char c : array) {
            int foundIndex = -1;
            for (int i = 0; i < lastIndex; i++) {
                if (countArr[i][0] == c) {
                    foundIndex = i;
                    break;
                }
            }
            if (foundIndex >= 0) {
                int a = countArr[foundIndex][1];
                countArr[foundIndex][1] = (char) ++a;
            } else {
                countArr[lastIndex][0] = c;
                countArr[lastIndex][1] = '1';
                lastIndex++;
            }
        }
        for (int i = 0; i < lastIndex; i++) {
            System.out.println(countArr[i][0] + " " + countArr[i][1]);
        }
    }
3
  • 4
    Whoops! Wrong language. Oct 24, 2018 at 10:23
  • 1
    This answer is not written in C++, because of that it doesn't answer the question.
    – jrh
    Aug 12, 2020 at 14:11
  • Please use the latest c++ code to minimize the code.
    – Nagappa
    Jun 17, 2022 at 5:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.