簡體   English   中英

C-用空格替換制表符,用1個空格替換多個空格,用1個換行符替換多個換行符

[英]C - Replace tabs with spaces, multiple spaces with 1 space, multiple newlines with 1 newline

我被要求寫一個簡單的程序來基於眾所周知的循環來“格式化”文本:

int c;
while ((c = getchar()) != EOF)
   putchar(c);

該程序從stdin讀取並寫入stdout,應使用I / O重定向進行測試。

  • 輸入中的每個選項卡都由一個空格替換,然后兩個或更多個連續的空格由輸出中的單個空格替換。

  • 輸入中的兩個或更多連續的空行被輸出中的一個空行替換。

注意:換行符是一行的最后一個字符,而不是下一行的第一個字符。

這是到目前為止的內容,但是輸入文本文件中的倍數空格,換行符和制表符不會在輸出文本文件中被替換:

#include <stdio.h>

int main (void){

int c;
int spacecount = 0;
int newlinecount = 0;

while ((c = getchar()) != EOF){

    if (c == '\n'){
        if (++newlinecount < 3){
            putchar(c);
        }
        continue;
    }

    newlinecount = 0;

    if (c == ' '){
        if (++spacecount < 2){
            putchar(c);
        }
        continue;   
    }

    spacecount = 0;

    if (c == '\t'){
        c = ' ';
    }
    putchar(c);
}

return 0;

}

刪除所有空白行並將所有制表符和空格壓縮到1個空格

您遇到的最大問題是,如果遇到' ''\\n'並需要用較小的數字替換多次出現的其中一個,則需要繼續讀取(此時在外部while循環內),直到找到不是' ''\\n'的字符。 這樣可以簡化對計數的跟蹤。 (並消除了對spacecountnewlinecount

由於您要針對多個字符進行測試,因此當您找到與當前搜索字符不匹配的第一個字符時,只需將其放回stdin並移至外部while循環的下一個迭代中即可。

將所有制表tabsspaces壓縮到單個space ,需要在單個if語句中測試tabspace

放在一起,您可以執行以下操作:

#include <stdio.h>

int main (void) {

    int c;

    while ((c = getchar ()) != EOF)
    {
        if (c == '\r') continue;
        if (c == '\n') {        /* handle newlines/carriage-returns */
            putchar (c);
            while ((c = getchar ()) == '\n' || c == '\r') {}
            if (c != EOF) ungetc (c, stdin); else break;
            continue;
        }
        if (c == ' ' || c == '\t') {  /* spaces & tabs */
            putchar (' ');
            while ((c = getchar ()) == ' ' || c == '\t') {}
            if (c != EOF) ungetc (c, stdin); else break;
            continue;
        }
        putchar (c);
    }
    return 0;
}

注意:代碼已更新,可以處理DOS / windoze \\r\\n行尾以及Linux '\\n'

輸入示例

$ cat dat/gcfmt.txt

N <tab> description
21      grapes
18      pickles



N <spaces> description
23         apples
51         banannas



<spaces>N<tab>  description
        8       cherries
        4       mellons
        6       strawberries


that's  all     folks   <tab separated>

that's  all     folks   <space separated>

樣品使用/輸出

使用相同的輸入文件,現在輸出為:

$ ./bin/gcfmt1 <dat/gcfmt.txt
N <tab> description
21 grapes
18 pickles
N <spaces> description
23 apples
51 banannas
<spaces>N<tab> description
 8 cherries
 4 mellons
 6 strawberries
that's all folks <tab separated>
that's all folks <space separated>

讓我知道您是否打算這樣做。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM