我想测量以下两件事:
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
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)
使用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.问题中未正确指定所需行为,因此我选择了一种可能性.