首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C語言多行輸入過濾:查找包含 "ould" 的行並打印

     編輯:關於C語言

C語言多行輸入過濾:查找包含 "ould" 的行並打印

從標準輸入讀取多行文本,調用自製 my_strstr 過濾包含 "ould" 的行並輸出。演示行讀取、字符串查找、流處理組合。

核心組件

  1. getline:安全讀取一行(含換行符)
  2. my_strstr:子串查找
  3. 主循環:讀取→過濾→輸出

完整代碼

#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 可替換為標準庫 strstr
  • while (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;
}
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved