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

问题描述 投票:0回答:15

如何计算像

"_"
这样的字符串中
"bla_bla_blabla_bla"
的数量?

c++ string pattern-matching
15个回答
551
投票
#include <algorithm>

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

// alternatively, in C++20
auto count = std::ranges::count(s, '_');

参见

std::count
std::ranges::count


40
投票

伪代码:

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.size()
替换为
strlen(s)
- 但将其分配给
for
循环之外的变量以避免扫描整个字符串在每个循环迭代中。

另请注意:我可以理解您想要“尽可能小”的东西,但我建议您改用此解决方案。如您所见,您可以使用函数来封装代码,这样您就不必每次都编写

for
循环,而可以在其余代码中使用
count_underscores("my_string_")
。在这里使用高级 C++ 算法当然是可能的,但我认为这是矫枉过正。


36
投票

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

#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:我很抱歉,我希望你能做对你的作业,尽管我的恶搞,像我这样的答案并没有阻止你参与该网站。


16
投票

使用 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;

15
投票
#include <boost/range/algorithm/count.hpp>

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

8
投票

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

using namespace boost::lambda;

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

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


8
投票

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

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

4
投票

std::string 有多种用于搜索的方法,但 find 可能就是您要寻找的。如果您指的是 C 风格的字符串,那么等效的就是 strchr。但是,无论哪种情况,您都可以使用 for 循环并检查每个字符 - 循环本质上就是这两者的总结。

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


4
投票

我会这样做:

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

2
投票

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

示例:

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

0
投票

我也会做类似的事情:)

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

0
投票

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

0
投票

C++23 中更简单(可能一些 C++20 编译器也支持)

    //Inputs : Your string,Search criteria
    int num_items = std::ranges::count("bla_bla_blabla_bla",'_');
    
    //Print output
    std::cout << num_items << std::endl; //3

-4
投票

尝试

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

-9
投票
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]);
        }
    }
© www.soinside.com 2019 - 2024. All rights reserved.