從 stdin 讀取多行,每行檢查是否包含子字串 "ould",包含則列印該行。EOF 結束 (Ctrl+D / Ctrl+Z)。
#define MAXLINE 1000
int my_getline(char *line, int lim) {
int c, i = 0;
while (--lim > 0 && (c = getchar()) != EOF && c != '\n')
line[i++] = c;
if (c == '\n') line[i++] = '\n';
line[i] = '\0';
return i;
}
char *my_strstr(const char *haystack, const char *needle) {
if (!*needle) return (char*)haystack;
for (; *haystack; haystack++) {
const char *h = haystack, *n = needle;
while (*h && *n && *h == *n) { h++; n++; }
if (!*n) return (char*)haystack;
}
return NULL;
}
int main() {
char line[MAXLINE];
const char *target = "ould";
while (my_getline(line, MAXLINE) > 0) {
if (my_strstr(line, target))
printf("%s", line); // line 已含 \n
}
return 0;
}
#include#include int main() { char line[1000]; while (fgets(line, sizeof(line), stdin)) if (strstr(line, "ould")) fputs(line, stdout); return 0; }