我怎么能计算“_”的数量在一个字符串像“bla_bla_blabla_bla”?


当前回答

#include <algorithm>

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

其他回答

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

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

基于范围的for循环很方便

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

你可以使用字符串函数找出源字符串中'_'的出现情况。 Find()函数有两个参数,第一个参数是我们想要找出其出现的字符串,第二个参数是起始位置。While循环用于在源字符串结束之前查找发生的情况。

例子:

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

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

我也会这么做:)

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