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

Jam*_*ame 4 c++ stdstring

我想测量以下两件事:

  • 多少次一个逗号出现在一个std ::性病,例如,如果str ="1,2,3,4,1,2," 然后str.Count(',')返回我6在上面的字符串的情况下,
  • 第二件事也类似于第一件事而不是单一字符我想要计算一个字符串的出现次数,例如 str.FindAllOccurancesOF("1,2,") 返回我2

在c ++中有没有用于计算的内置函数,或者我需要为此编写自定义代码?

Mah*_*esh 9

关于第一个 -

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

编辑:

使用string :: find -

#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 ;
}
Run Code Online (Sandbox Code Playgroud)

IdeOne结果


jua*_*nza 5

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

}
Run Code Online (Sandbox Code Playgroud)

编辑:此函数不允许重叠,即在字符串"AA"中搜索子字符串"AAAAAAAA"计数4.为了允许重叠,这一行

pos += step
Run Code Online (Sandbox Code Playgroud)

应该被替换

++pos
Run Code Online (Sandbox Code Playgroud)

这将导致计数7.问题中未正确指定所需行为,因此我选择了一种可能性.