编写函数int StrCount(char *str1,char *str2),其功能是统计字符串str2在str1中出现的次数,返回该数值。要求:在主函数中输入str1和str2,调用函数StrCount(str1,str2)后输出结果(例如,输入str1为”howareyouareGGGare”,str2为”are”,调用函数StrCount后的函数返回值为3,输出结果为3)。
时间: 2024-03-21 22:40:47 浏览: 26
好的,这是一个比较简单的字符串统计问题,下面是对应的函数实现:
```c++
#include <iostream>
#include <cstring>
using namespace std;
int StrCount(char *str1, char *str2) {
int count = 0;
int len1 = strlen(str1);
int len2 = strlen(str2);
for (int i = 0; i <= len1 - len2; i++) {
bool found = true;
for (int j = 0; j < len2; j++) {
if (str1[i + j] != str2[j]) {
found = false;
break;
}
}
if (found) {
count++;
}
}
return count;
}
int main() {
char str1[100], str2[100];
cout << "请输入str1和str2:" << endl;
cin >> str1 >> str2;
int count = StrCount(str1, str2);
cout << "字符串" << str2 << "在" << str1 << "中出现了" << count << "次" << endl;
return 0;
}
```
函数的主要思路是:先用两个变量存储字符串的长度,然后使用两重循环遍历字符串,找到匹配的子串,统计次数即可。需要注意的是,在判断是否找到匹配子串时,我们使用了一个bool类型的变量found,如果是,说明找到了匹配子串,将计数器count加1。
测试样例:
- 输入:howareyouareGGGare are
- 输出:字符串are在howareyouareGGGare中出现了3次