给定两个字符串a,b,编写函数求字符串b在字符串a中出现的次数
代码如下:存放位置不需要的话就去掉
#include <stdio.h>
#include <string.h>
#include <ctype.h>
//查找big串中所有smal串的位置,并把位置存放在pos中,nmb存放个数
int findstr(char*big ,char* smal)
{
int nmb = 0;
int i,j,lenb,lens;
lenb = strlen(big);
lens = strlen(smal);
if(lens > lenb)
return 0;
i = 0;
while(i < lenb-lens+1)
{
for (j = 0; j < lens;j++)
{
if(tolower(big[i+j]) != tolower(smal[j]))
break;
}
if (j == lens) //说明找到
{
//pos[*nmb] = i;
nmb++;
i += lens;
}else
i++;
}
}
int main()
{
char big[100]={0};
char sml[20]={0};
//int pos[20];
int nmb;
printf("请输入长字符串:");
gets(big);
printf("请输入需要查找的单词:");
gets(sml);
nmb = findstr(big,sml);
printf("出现次数:%d\n",nmb);
return 0;
}
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
int main()
{
string a, b;
cin >> a >> b;
int res = 0;
for (int i = 0; i<a.length() - b.length() + 1; i++)
{
if (b == a.substr(i, b.length()))
{
res++;
}
}
cout << res << endl;
system("pause");
return 0;
}