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

C語言終端多行輸入處理:查找包含 "ould" 的行並列印 (getline + strstr)

     編輯:關於C

核心需求

從 stdin 讀取多行,每行檢查是否包含子字串 "ould",包含則列印該行。EOF 結束 (Ctrl+D / Ctrl+Z)。

手寫 getline (安全讀行)

#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;
}

手寫 strstr (子字串查找)

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;
}
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved