例如:字符串str=“110\n120\n130\n140”,查找的子串s="\n", 得到子串s在字符串str的出现次数为:3
函数如下:
#include <iostream>
#include <string>
int getSubstrNum(const std::string& str, const std::string& s)
{
int sLength=s.size();//子串长度
int index=0;
int endIndex=str.find(s,index);
int num=0;
while(endIndex>0)
{
num++;
if(endIndex>index)
{
index=endIndex+sLength;
}
endIndex=str.find(s,index);
}
return num;
}