從標準輸入讀取多行文本,調用自製 my_strstr 過濾包含 "ould" 的行並輸出。演示行讀取、字符串查找、流處理組合。
getline:安全讀取一行(含換行符)my_strstr:子串查找#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LINE 1000
// 安全讀取一行,返回長度,EOF 返回 0
int get_line(char *line, int limit) {
int ch, i = 0;
while (limit-- > 0 && (ch = getchar()) != EOF && ch != '\n') {
line[i++] = ch;
}
if (ch == '\n') line[i++] = '\n';
line[i] = '\0';
return i;
}
// 子串查找(標準 strstr 行為)
char *my_strstr(const char *haystack, const char *needle) {
assert(haystack && needle);
if (*needle == '\0') return (char *)haystack;
const char *h = haystack;
while (*h) {
const char *h_start = h;
const char *n = needle;
while (*h && *n && *h == *n) { h++; n++; }
if (*n == '\0') return (char *)h_start;
h = h_start + 1;
}
return NULL;
}
int main() {
char line[MAX_LINE];
const char *target = "ould";
while (get_line(line, MAX_LINE - 1) > 0) {
if (my_strstr(line, target)) {
printf("%s", line); // line 已含換行符
}
}
system("pause");
return 0;
}
輸入: could you help me? this is a test would you like tea? should we go? END 輸出: could you help me? would you like tea? should we go?
get_line 處理 EOF、換行符、緩衝區邊界my_strstr 可替換為標準庫 strstrwhile (get_line(...) > 0) 以長度 > 0 作為繼續條件printf("%s", line) 避免雙重換行const char *keywords[] = {"ould", "ing", "the", NULL};
bool match_any(const char *line) {
for (int i = 0; keywords[i]; i++) {
if (my_strstr(line, keywords[i])) return true;
}
return false;
}