簡體   English   中英

如何使用 putchar “擠壓”字符(Ansi-C)

[英]How do I use putchar to “squeeze” characters (Ansi-C)

我想知道是否可以為我的代碼獲得一些幫助。 我在下面放了一些部分代碼

/*reads char by char til EOF*/
while((c = getchar()) != EOF)
{

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

我現在要做的是擠壓用戶輸入的空格字符。 因此,如果用戶輸入:

a[空間][空間][空間][空間][空間][空間][空間][空間]a

output 應該只是

a[空間]a

現在我已經設置它替換 d 的所有空格以用於測試目的。 我將如何更改我的代碼,以便它只打印出 1 個空格而不是用戶輸入的所有空格。

感謝您提前提供任何幫助。

只需保留一個空格標志:

int lastWasSpace = 0;
while((c = getchar()) != EOF) {
    if(c == '\t' || c == ' ') { // you could also use isspace()
        if(!lastWasSpace) {
            lastWasSpace = 1;
            putchar(c);
        }
    } else {
        lastWasSpace = 0;
    }
}

一種解決方案:

/*reads char by char til EOF*/
int hasspace = 0;

while((c = getchar()) != EOF)
{
    if (isspace(c))
        hasspace = 1;
    }
    else
    {
        if (hasspace)
        {
            hasspace = 0;
            putchar(' ');
        }
        putchar(c);
    }     
}
jcomeau@intrepid:/tmp$ cat compress.c; echo 'this     is    a  test' | ./compress 
#include <stdio.h>
int main() {
 int c, lastchar = 'x';
 while ((c = getchar()) != EOF) {
  if (c == '\t' || c == ' ') {
   if (lastchar != ' ') {
    putchar(' ');
    lastchar = ' ';
   }
  } else {
   putchar(c);
   lastchar = c;
  }
 }
}
this is a test

首先,您是如何聲明c

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

如果cchar ,那么它不能包含所有字符EOF 確保使用大於char的數據類型聲明c (通常為int )。

接下來,您可以使用一個便宜的技巧來處理壓縮多個空格:

int space_seen = 0;

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

    if(c == '\t')
    {
        putchar(' ');
    }
    else if(c == ' ')
    {
        if (!space_seen)
        {
            putchar('d');
            space_seen = 1;
        }
    }
    else
    {
        putchar(c);
        space_seen = 0;
    }
}

這個技巧也適用於跟蹤解析字符串。

記錄打印空格的時間,在找到另一個字母之前不要再打印它們。

使用您的代碼作為基礎:

unsigned char space = 0;

/* reads char by char until EOF */
while((c = getchar()) != EOF)
{
    if(c == '\t')
    {
        putchar(' ');
    }
    else if(c == ' ')
    {
        /* state specific action */
        if(space == 0) {
            putchar('d');
            space = 1; /* state transition */
        }
    }
    else
    {
        /* state transition */
        if(space == 1) {
            space = 0;
        }

        putchar(c);
    }
}

那里有 go。 一個非常非常簡單的 state 機器。 就這么簡單!

暫無
暫無

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

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