给出两个字符串A和B,字符串中只包含‘0’和‘1’。编写程序,可重复多次操作,给出B字符串中包含A字符串的次数,例如A为“11”,B为“1001110110”,则应打印为3。
方法一
#include<iostream>
#include<string>
using namespace std;
int main()
{
string s1,s2;
int n;
cin>>n;
while(n--)
{
cin>>s1>>s2;
unsigned int m=s2.find(s1,0); //string类find方法,从s1[0]位置寻找s1的字串s2,找到返回位置,没找到返回string::npos
int num=0;
while(m!=string::npos)
{
num++;
m=s2.find(s1,m+1);
}
cout<<num<<endl;
}
} 方法二
#include<iostream>
using namespace std;
int main()
{
int N, count = 0;
cin >> N;
char str1[100], str2[100], *p1, *p2, *p3;
while (N--){
count = 0;
cin >> str1;
cin >> str2;
p1 = str1;
p2 = str2;
while (*p2){
if (*p1 == *p2){
p3 = p2;
while (*p1){
if (*p1 != *p2){
p1 = str1;
p2 = p3;
break;
}
p1++;
p2++;
}
if (!*p1){
p1 = str1;
p2 = p3;
count++;
}
}
p2++;
}
cout << count << endl;
}
system("pause");
return 0;
}
本文介绍两种计算一个字符串(仅包含'0'和'1')作为子串在另一个字符串中出现次数的方法。方法一使用C++标准库中的string类及其find方法;方法二采用指针遍历的方式实现。
487

被折叠的 条评论
为什么被折叠?



