在线编译器 C

#include <stdio.h> int main() { char text[1001]; char pattern[101]; fgets(text, sizeof(text), stdin); fgets(pattern, sizeof(pattern), stdin); int count = 0; int i = 0; int j; while (text[i] != '\0' && text[i] != '\n') { j = 0; while (pattern[j] != '\0' && pattern[j] != '\n' && text[i + j] == pattern[j]) { j++; } if (pattern[j] == '\0' || pattern[j] == '\n') { count++; } i++; } printf("%d", count); return 0; }
This code counts how many times a pattern string appears as a substring in a text string. It reads two lines from input, then scans through the text character by character, checking if the pattern matches starting at each position.

- The condition `pattern[j] == '\0' || pattern[j] == '\n'` checks if the entire pattern was matched, but it does not account for the case where the pattern ends with a newline from `fgets`. This can cause incorrect counting when the pattern is shorter than the buffer.
- The inner loop stops when `text[i + j] == pattern[j]` fails, but it does not check if `text[i + j]` is the null terminator or newline, which could lead to reading beyond the string bounds.