andre de boer
andre de boer

Reputation: 3284

Count character occurrences in a string in C++

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

Upvotes: 288

Views: 504286

Answers (13)

Benoit
Benoit

Reputation: 79165

#include <algorithm>

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

// alternatively, in C++20
auto count = std::ranges::count(s, '_');

See std::count and std::ranges::count.

Upvotes: 576

schnaader
schnaader

Reputation: 49719

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) - but assign that to a variable outside the for loop to avoid scanning the whole string on every loop iteration.

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.

Upvotes: 40

Pavan Chandaka
Pavan Chandaka

Reputation: 12731

Much simpler in C++23 (May be some C++20 compilers also support)

    //Inputs : Your string,Search criteria
    int num_items = std::ranges::count("bla_bla_blabla_bla",'_');
    
    //Print output
    std::cout << num_items << std::endl; //3

Upvotes: 0

Shivam Jha
Shivam Jha

Reputation: 192

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;
}

Upvotes: 4

epix
epix

Reputation: 147

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;
}

Upvotes: 0

Nagappa
Nagappa

Reputation: 313

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;

Upvotes: 17

FruityFred
FruityFred

Reputation: 249

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

Upvotes: 0

Md. Sakib Hossain
Md. Sakib Hossain

Reputation: 245

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;
}

Upvotes: 8

Amruta Ghodke
Amruta Ghodke

Reputation: 115

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();
} 

Upvotes: 2

user1977268
user1977268

Reputation: 151

#include <boost/range/algorithm/count.hpp>

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

Upvotes: 15

Software_Designer
Software_Designer

Reputation: 8587

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;
}

Upvotes: -5

Roger Pate
Roger Pate

Reputation:

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.

Upvotes: 4

Diego Sevilla
Diego Sevilla

Reputation: 29011

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...

Upvotes: 8

Related Questions