为什么测试结果还是43
时间: 2023-09-03 18:07:39 浏览: 41
非常抱歉,我之前理解您的问题有误,没有完全理解您的意思。修改后的代码已经解决了长度限制的问题,但是您输入的测试数据中,子串和长串之间有一个空格,而原来的代码中并没有考虑空格的情况。因此,程序在匹配子串和长串时会将空格也视为一个字符,导致结果不正确。
为了解决这个问题,需要在匹配子串和长串时,忽略空格,只匹配非空格字符。具体实现方法是在第二层循环中加入一个判断条件,如果当前字符是空格,则直接跳过,继续匹配下一个字符。以下是修改后的代码:
```c++
#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);
// 输入子串,限制长度为128
cin.getline(str,1024);
// 输入长串,限制长度为1024
int n = frequency(sub,str);
// 调用frequency函数,计算子串在长串中出现的次数
cout<<n<<endl;
// 输出次数
return 0;
}
// 函数frequency:计算子串在长串中出现的次数
// 参数:substr-指向子串,str-指向长串
// 返回值:出现的次数
int frequency(char * substr, char * str) {
int n = strlen(substr);
int m = strlen(str);
int count = 0;
for (int i = 0; i <= m - n; i++) {
bool match = true;
for (int j = 0; j < n; j++) {
if (substr[j] != str[i+j] && str[i+j] != ' ') {
match = false;
break;
}
}
if (match) {
count++;
}
}
return count;
}
```
请注意,这个修改仅适用于输入数据中包含空格的情况。如果输入的子串和长串中包含其他的特殊字符,需要根据实际情况进行修改。