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

C++ How to calculate the number time a string occurs in a data

本文关键字:数据 字符串 何计算 计算 C++      更新时间:2023-10-16

我想测量以下两件事:

  • 逗号在std::std,例如 if str ="1,2,3,4,1,2,"那么str.Count(',')在上述情况下6返回我字符串
  • 第二件事也类似于第一个打开,而不是单个我想计算数字的字符字符串的出现次数,例如 str.FindAllOccurancesOF("1,2,")还给我2

c++ 中是否有任何内置函数来计算这个,或者我需要为此编写自定义代码?

关于第一个 -

std::string str="1,2,3,4,1,2," ;
std::count( str.begin(), str.end(), ',' ) ; // include algorithm header

编辑:

使用字符串::查找 -

#include <string>
#include <iostream>
using namespace std;
int main()
{
        string str1 = "1,2,3,1,2,1,2,2,1,2," ;
        string str2 = "1,2," ;
        int count = 0 ;
        int pos = -4;
        while( (pos = str1.find(str2, pos+4) ) != -1 ) // +4 because for the next 
                                                       // iteration current found
                                                       // sequence should be eliminated
        {
            ++count ;         
        }
        cout << count ;
}

IdeOne 结果

使用 std::string::find 方法之一,可以单步执行引用字符串,每次找到子字符串时计数。无需复制或擦除。此外,使用 std::string::npos 检查是否已找到模式,而不是文字-1。此外,使用子字符串的大小 std::string::size() 避免对步长进行硬编码(其他答案中的文字4

size_t stringCount(const std::string& referenceString,
                   const std::string& subString) {
  const size_t step = subString.size();
  size_t count(0);
  size_t pos(0) ;
  while( (pos=referenceString.find(subString, pos)) !=std::string::npos) {
    pos +=step;
    ++count ;
  }
  return count;
}

编辑:此功能不允许重叠,即在字符串"AAAAAAAA"中搜索子字符串"AA"会导致计数4。为了允许重叠,此行

pos += step

应替换为

++pos

这将导致计数为 7 。问题中没有正确指定所需的行为,所以我选择了一种可能性。

如果您使用的是char*(C 样式)字符串,则可以尝试以下(伪代码):对于出现的字符计数:

const char *str ="1,2,3,4,1,2,", *p = str - 1;
int count = 0
while(0 != (p = strchr(++p, ',')))
  count ++;

对于发生的计数字符串:

const char *str ="1,2,3,4,1,2,", *p = str - 1;
int count = 0;
while(0 != (p = strstr(++p, "1,2,")))
  count ++;

string::find() 将带您上路。