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


当前回答

我会这样做:

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

其他回答

你能想到的……Lambda版本……:)

using namespace boost::lambda;

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

你需要几个include…我把这个留给你们做练习。

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

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

具有适当命名变量的老式解决方案。这给了代码一些精神。

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

编辑:大约8年后,看到这个答案,我为自己这么做感到羞愧(尽管我对自己说,这是对一个不费力气的问题的讽刺)。这是有害的,是不好的。我不是要移除这根柱子;我添加这个道歉是为了帮助改变StackOverflow上的气氛。所以OP:我道歉,我希望你的作业是正确的,尽管我的喷子,像我这样的答案并没有阻止你参与网站。

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

使用lambda函数检查字符是否为“_”,则唯一的计数将增加,否则不是有效字符

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;