在线编译器 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(char s[]) { int i = 0; int size = length(s); while (i < size) { if (s[i] == '\n') { s[i] = '\0'; return; } i++; } } int main() { char a[1001]; char b[1001]; fgets(a, 1001, stdin); fgets(b, 101, stdin); remove_newline(a); remove_newline(b); printf("%d", result(a, b)); return 0; }
这段代码的功能是:从标准输入读取两行字符串,然后统计字符串b在字符串a中作为连续子串出现的次数,并输出这个次数。

代码中定义了几个函数:length用于计算字符串长度,result用于统计子串出现次数,remove_newline用于去除字符串末尾的换行符。主函数中读取两个字符串,去除换行符后调用result函数并输出结果。

- 在main函数中,数组b的大小声明为1001,但fgets读取时限制为101,这可能导致读取不完整。检查fgets的第二个参数是否应该与数组大小一致。
- result函数中的循环条件`i < size_a - size_b + 1`在size_b为0时会有问题,但这里size_b至少为1(因为fgets至少会读入换行符,但被去除了)。不过如果b是空字符串,需要额外考虑边界情况。