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


当前回答

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

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

其他回答

std::string有几个用于搜索的方法,但find可能是你要找的。如果您指的是c风格的字符串,那么等效的是strchr。然而,在这两种情况下,您也可以使用for循环并检查每个字符—循环本质上是这两个字符的结义。

一旦你知道如何找到给定起始位置的下一个字符,你就可以不断地推进搜索(即使用循环),一边计算一边计算。

我也会这么做:)

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

我会这样做:

#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函数检查字符是否为“_”,则唯一的计数将增加,否则不是有效字符

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;
#include <boost/range/algorithm/count.hpp>

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