在线编译器 C

#include <stdio.h> #include <string.h> int length(char s[]) { int i = 0; while (s[i] != '\0') { i++; } return i; } int result(char a[], char b[]) { int size_a = length(a); int size_b = length(b); int counter = 0; if (size_a >= size_b) { for (int i = 0; i < size_a - size_b + 1; i++) { int sum = 0; for (int j = 0; j < size_b; j++) { if (a[i + j] == b[j]) { sum++; } } if (sum == size_b) { counter++; } } } return counter; } void remove_newline(*s) { while (*s) { if (*s == '\n') { *s = '\0'; return; } s++; } } int main() { char a[1001]; char b[101]; fgets(a, 1001, stdin); fgets(b, 1001, stdin); remove_newline(a); remove_mewline(b); printf("%d", result(a, b)); return 0; }
这段代码的功能是:从标准输入读取两行字符串,然后统计字符串b在字符串a中出现的次数(不重叠的子串匹配)。代码中定义了几个函数:length计算字符串长度,result统计子串出现次数,remove_newline去除换行符。

代码中存在几个问题:

- 在main函数中,调用remove_newline时,参数传递方式不正确。函数定义中参数类型是`*s`,但缺少类型说明,应该是指针类型。同时,调用时应该传入字符串的地址,但当前写法可能不匹配。

- 在main函数中,有一行`remove_mewline(b);`,这里函数名拼写错误,应该是`remove_newline`,而且参数传递方式同样需要修正。

- 另外,fgets读取b时,第二个参数是1001,但b数组大小只有101,这会导致缓冲区溢出。应该将第二个参数改为101或更小。