// 包含字符串函数库 #include <string.h> #include <iostream> using namespace std; int frequency(char * substr, char * str); int main() { char sub[128],str[1024]; cin.getline(sub,128); // 输入子串 cin.getline(str,1024); // 输入长串 int n = frequency(sub,str); // 调用frequency函数,计算子串在长串中出现的次数 cout<<n<<endl; // 输出次数 return 0; } // 函数frequency:计算子串在长串中出现的次数 // 参数:substr-指向子串,str-指向长串 // 返回值:出现的次数 int frequency(char * substr, char * str) { // 请在此添加代码,实现函数frequency /********** Begin *********/ int n=0; char *p=substr; int l1=strlen(substr); int l2=strlen(str); while(true){ if(strstr(substr+(p-substr),str)!=NULL){ p=strstr(substr+(p-substr),str); p=p+l2; if(l1-(p-substr)<l2){ n++; break; } else n++; } else break; } return n; /********** End **********/ }这段代码无法正确返回子串在字符串中出现的次数,问题出在哪?
时间: 2023-11-14 10:07:06 浏览: 40
这段代码中存在以下问题:
1. 在函数`frequency()`中,`substr`指向的是子串的首地址,而在`while`循环中,又将其当作长串的一部分,应该将`str`和`substr`的位置颠倒,即将`substr`当作长串,将`str`当作子串。
2. 在`while`循环中,`strstr()`函数的第一个参数应该是长串,第二个参数应该是子串,而当前的代码中却是反过来的。
3. 在`while`循环中,当子串在长串中出现时,计数器`n`应该加1,而当前的代码中却是在子串长度小于或等于长串剩余部分的时候才加1,这样会导致最后一个子串没有被计数。
修改后的代码如下:
```c++
#include <string.h>
#include <iostream>
using namespace std;
int frequency(char * str, char * substr);
int main() {
char str[1024], substr[128];
cin.getline(str, 1024);
cin.getline(substr, 128);
int n = frequency(str, substr);
cout << n << endl;
return 0;
}
int frequency(char * str, char * substr) {
int n = 0;
char *p = str;
int l1 = strlen(str);
int l2 = strlen(substr);
while (true) {
p = strstr(p, substr);
if (p != NULL) {
n++;
p += l2;
if (p - str + l2 > l1) {
break;
}
} else {
break;
}
}
return n;
}
```
注意到我们在`while`循环内部先使用`strstr()`函数查找子串在长串中的位置,如果找到了,则计数器`n`加1,然后将`p`指向子串后面的位置。接着判断`p`指向的位置是否已经超出了长串的末尾,如果是则跳出循环。如果没有找到子串,则直接跳出循环。
相关推荐
![cpp](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)