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


当前回答

基于范围的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;
}

其他回答

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

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

伪代码:

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++算法当然是可行的,但我认为这太过了。

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

public static void main(String[] args) {
        char[] array = "aabsbdcbdgratsbdbcfdgs".toCharArray();
        char[][] countArr = new char[array.length][2];
        int lastIndex = 0;
        for (char c : array) {
            int foundIndex = -1;
            for (int i = 0; i < lastIndex; i++) {
                if (countArr[i][0] == c) {
                    foundIndex = i;
                    break;
                }
            }
            if (foundIndex >= 0) {
                int a = countArr[foundIndex][1];
                countArr[foundIndex][1] = (char) ++a;
            } else {
                countArr[lastIndex][0] = c;
                countArr[lastIndex][1] = '1';
                lastIndex++;
            }
        }
        for (int i = 0; i < lastIndex; i++) {
            System.out.println(countArr[i][0] + " " + countArr[i][1]);
        }
    }