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


当前回答

伪代码:

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

c++示例代码:

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

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

  return count;
}

注意,这是与std::string一起使用的代码,如果你使用char*,将s.s size()替换为strlen(s)。

另外注意:我可以理解你想要“尽可能小”的东西,但我建议你使用这个解决方案。正如你所看到的,你可以使用一个函数来封装代码,这样你就不必每次都写出for循环,但可以在剩下的代码中使用count_下划线("my_string_")。在这里,使用高级c++算法当然是可行的,但我认为这太过了。

其他回答

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

#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:我道歉,我希望你的作业是正确的,尽管我的喷子,像我这样的答案并没有阻止你参与网站。

我也会这么做:)

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

你能想到的……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, '_');

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