《C程序設計語言》練習1-9

問題:編寫一個將輸出複製到輸入的程序,並將其中的連續的多個空格用一個空格代替。

本例關鍵是要認識如何更新前一個字符及if-else語句,邏輯或的運用!

if語句實現:

#include <stdio.h>
#define NOBLANK 'a'
/* replace string of blanks with a single blank    */
int main()
{
    int c, lastc;
    lastc = NOBLANK;
    while((c = getchar()) != EOF) {
        if(c != ' ')            //輸出非空格字符
            putchar(c);
        if(c == ' ')            //處理空格字符
            if(lastc != ' ')    //檢查當前的空格字符究竟是一個單個的空格還是一串空格中的第一個空格
                putchar(c);
        lastc = c;              //更新上一個字符
    }
    return 0;
}

if-else實現:

#include <stdio.h>
#define NOBLANK 'a'
/* replace string of blanks with a single blank    */
int main()
{
    int c, lastc;
    lastc = NOBLANK;
    while((c = getchar()) != EOF) {
        if(c != ' ')            //輸出非空格字符
            putchar(c);
        else if(lastc != ' ')   //若上一個字符非空格則輸入本字符
            putchar(c);
        lastc = c;              //更新上一個字符
    }
    return 0;
}
邏輯或(OR)操作符 | | 實現:

 

#include <stdio.h>
#define NOBLANK 'a'
/* replace string of blanks with a single blank    */
int main()
{
    int c, lastc;
    lastc = NOBLANK;
    while((c = getchar()) != EOF) {
        if(c != ' ' || lastc != ' ') //本字符不是空格或者前一個字符不是空格則輸出
            putchar(c);
    }
    return 0;
}



發佈了37 篇原創文章 · 獲贊 3 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章