在 C++ 中计算字符串中的字符出现次数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3867890/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 13:56:11  来源:igfitidea点击:

Count character occurrences in a string in C++

c++stringpattern-matching

提问by andre de boer

How can I count the number of "_"in a string like "bla_bla_blabla_bla"?

如何计算"_"字符串中的数量"bla_bla_blabla_bla"

回答by Benoit

#include <algorithm>

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

回答by schnaader

Pseudocode:

伪代码:

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

EDIT: C++ example code:

编辑:C++ 示例代码:

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

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

  return count;
}

Note that this is code to use together with std::string, if you're using char*, replace s.size()with strlen(s).

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

Also note: I can understand you want something "as small as possible", but I'd suggest you to use this solution instead. As you see you can use a function to encapsulate the code for you so you won't have to write out the forloop everytime, but can just use count_underscores("my_string_")in the rest of your code. Using advanced C++ algorithms is certainly possible here, but I think it's overkill.

另请注意:我可以理解您想要“尽可能小”的东西,但我建议您改用此解决方案。如您所见,您可以使用函数为您封装代码,这样您就不必for每次都写出循环,而可以count_underscores("my_string_")在其余代码中使用。在这里使用高级 C++ 算法当然是可能的,但我认为这太过分了。

回答by Tamás Szelei

Old-fashioned solution with appropriately named variables. This gives the code some spirit.

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

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


Edit: about 8 years later, looking at this answer I'm ashamed I did this (even though I justified it to myself as a snarky poke at a low-effort question). This is toxic and not OK. I'm not removing the post; I'm adding this apology to help shifting the atmosphere on StackOverflow. So OP: I apologize and I hope you got your homework right despite my trolling and that answers like mine did not discourage you from participating on the site.

编辑:大约 8 年后,看着这个答案,我很惭愧我这样做了(尽管我认为这是对一个轻松问题的尖刻戳戳)。这是有毒的,而且不好。我不会删除帖子;我添加这个道歉是为了帮助改变 StackOverflow 上的气氛。所以 OP:我很抱歉,我希望你的作业做对了,尽管我一直在拖钓,而且像我这样的答案并没有阻止你参与这个网站。

回答by user1977268

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

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

回答by Diego Sevilla

You name it... Lambda version... :)

你的名字... Lambda 版本... :)

using namespace boost::lambda;

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

You need several includes... I leave you that as an exercise...

你需要几个包括......我把它留给你作为练习......

回答by Nagappa

Using the lambda function to check the character is "_" then only count will be incremented else not a valid character

使用 lambda 函数检查字符是否为“_”,然后只会增加计数,否则不是有效字符

std::string s = "a_b_c"; size_t count = std::count_if( s.begin(), s.end(), []( char c ){if(c =='_') return true; }); std::cout << "The count of numbers: " << count << std::endl;

std::string s = "a_b_c"; size_t count = std::count_if( s.begin(), s.end(), []( char c ){if(c =='_') return true; }); std::cout << "The count of numbers: " << count << std::endl;

回答by Md. Sakib Hossain

Count character occurrences in a string is easy:

计算字符串中出现的字符很容易:

#include <bits/stdc++.h>
using namespace std;
int main()
{
    string s="Sakib Hossain";
    int cou=count(s.begin(),s.end(),'a');
    cout<<cou;
}

回答by Md. Sakib Hossain

There are several methods of std::string for searching, but find is probably what you're looking for. If you mean a C-style string, then the equivalent is strchr. However, in either case, you can also use a for loop and check each character—the loop is essentially what these two wrap up.

std::string 有多种搜索方法,但 find 可能是您要查找的方法。如果您的意思是 C 风格的字符串,那么等价物是 strchr。然而,在任何一种情况下,您也可以使用 for 循环并检查每个字符——循环本质上是这两个循环的结束。

Once you know how to find the next character given a starting position, you continually advance your search (i.e. use a loop), counting as you go.

一旦您知道如何在给定起始位置的情况下找到下一个字符,您就可以不断推进搜索(即使用循环),边走边数。

回答by Amruta Ghodke

You can find out occurrence of '_' in source string by using string functions. find() function takes 2 arguments , first - string whose occurrences we want to find out and second argument takes starting position.While loop is use to find out occurrence till the end of source string.

您可以使用字符串函数找出源字符串中 '_' 的出现。find() 函数接受 2 个参数,第一个 - 我们想要找出其出现的字符串,第二个参数取起始位置。而循环用于找出直到源字符串末尾的出现。

example:

例子:

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

回答by Shivam Jha

I would have done this way :

我会这样做:

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