Онлайн компилятор 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++; } s[i-1]='\0'; return; } int main() { char a[1001]; char b[101]; 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并输出结果。

- 在remove_newline函数中,最后的s[i-1]='\0'这一行可能有问题。当字符串中没有换行符时,循环会遍历到末尾,此时i等于size,但s[i-1]已经是字符串的最后一个字符,这样修改可能会意外截断字符串。你需要思考一下,当字符串中没有换行符时,应该如何处理。
- 在result函数中,你使用了两层循环来比较子串,思路是正确的。但注意,当size_a小于size_b时,函数直接返回0,这符合逻辑。不过,如果两个字符串长度相等,循环条件size_a - size_b + 1会变成1,循环执行一次,这也是正确的。