// 包含字符串函数库 #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,l=strlen(str); //char *sptr; while(*substr!='\0') { char *sptr=strstr(substr,str); if(sptr != NULL) { n++; substr=sptr+l; } else break; } return n; /********** End **********/ }这段代码有什么问题
时间: 2023-07-23 20:36:28 浏览: 52
这段代码存在一个潜在的问题:如果子串中包含长串中的一个字符,但是并不是完整的子串,那么函数仍然会将其计数为出现次数。
例如,当长串为 "abcd",子串为 "b" 时,函数会将其计数为 1,而实际上 "b" 并不是完整的子串。
为了解决这个问题,可以在 while 循环中添加一个判断条件,判断查找到的子串是否与目标子串完全匹配。只有当两个子串完全匹配时才将计数器加一,否则将子串指针更新到下一个可能的位置。
修改后的代码如下:
```
int frequency(char * substr, char * str) {
int n = 0, l = strlen(str);
while (*substr != '\0') {
char *sptr = strstr(substr, str);
if (sptr != NULL) {
// 判断查找到的子串是否与目标子串完全匹配
if (strncmp(sptr, substr, strlen(substr)) == 0) {
n++;
}
substr = sptr + 1;
} else {
break;
}
}
return n;
}
```
这样就可以避免上述问题。
相关问题
#include <iostream.h> #include <string.h> #include <algorithm.h> #include <bitset.h> #include <vector.h>这五个引用的是什么
这五个引用分别是C++标准库中的头文件,包含了不同的函数和类,具体如下:
1. #include <iostream.h>:数据流输入/输出,包含了cin、cout等对象和相关操作符。
2. #include <string.h>:C语言中处理字符串的头文件,包含了字符串操作函数。
3. #include <algorithm.h>:STL中的头文件,包含了各种算法函数,如排序、查找等。
4. #include <bitset.h>:STL中的头文件,包含了位集合类bitset。
5. #include <vector.h>:STL中的头文件,包含了动态数组类vector。
#include <stdlib.h> #include <iostream.h> #include <fstream.h>
#include <stdlib.h>:这是C/C++标准库中的一个头文件,它包含了一些常用的函数和宏定义,用于处理内存分配、随机数生成、字符串转换等操作。
#include <iostream.h>:这是C++标准库中的一个头文件,它包含了输入输出流的定义和相关操作符的重载,用于进行控制台输入输出。
#include <fstream.h>:这是C++标准库中的一个头文件,它包含了文件输入输出流的定义和相关操作符的重载,用于进行文件的读写操作。
这些头文件在C/C++编程中经常使用,可以帮助我们进行各种输入输出操作和文件处理操作。
范例:
```cpp
#include <stdlib.h>
#include <iostream.h>
#include <fstream.h>
int main() {
// 使用stdlib.h中的函数
int num = rand(); // 生成一个随机数
cout << "Random number: " << num << endl;
// 使用iostream.h中的函数
int input;
cout << "Enter a number: ";
cin >> input;
cout << "You entered: " << input << endl;
// 使用fstream.h中的函数
ofstream file("example.txt"); // 创建一个文件对象
file << "This is an example." << endl; // 写入文件
file.close(); // 关闭文件
return 0;
}
```