第一章8~12

1.8

#include <stdio.h>

int main(){
    int c;
    int space = 0;
    int tab = 0;
    int nextline = 0;
    while((c=getchar())!=EOF){
        switch(c){
            case ' ':
                space++;
                break;
            case '\n':
                nextline++;
                break;
            case '\t':
                tab++;
                break;
            default:
                break;
        }
    }
    printf("space=%d, tab=%d, nextline=%d\n", space, tab, nextline);
}

1.9

/* 解法一*/
#include <stdio.h>
#include <stdbool.h>
#include <ctype.h>

int main(){
    int c;
    bool flag = false;
    while((c = getchar()) != EOF){
        if(isalnum(c)){
            flag = true;
            printf("%c", c);
        } else if(' ' == c && flag){
            flag = false;
            printf("%c", ' ');
        }
    }
    return 0;
}

/*第二种解法*/
#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 ;
    }
}

1.10

#include <stdio.h>


int  main(){
    int c;
    while((c = getchar()) != EOF){
        switch(c){
            case '\t':
                printf("\\t");
                break;
            case '\b':
                printf("\\b");
                break;
            case '\\':
                printf("\\\\");
                break;
            default:
                printf("%c", c);
                break;
        }
    }
    return 0;
}

1.11

1.12

/*解法一*/
#include <stdio.h>

void display(char s[]);

int main(){
    char s[128];
    printf("Please a string you want print: ");
    fgets(s, 127, stdin);
    display(s);
    printf("%s", s);
    return 0;
}

void display(char s[]){
    int i = 0;
    int j = 0;
    char lastc = 'a';
    for(i = 0; s[i] != '\0'; i++){
        if(s[i] != ' '){
            s[j++] = s[i];
        } else if(lastc != '\n' && lastc != ' '){
            s[i] = '\n';
            s[j++] = s[i];
        }
        lastc = s[i];
    }
    s[j] = '\0';
}

/*解法二*/
#include <stdio.h>

#define IN 1 /* inside a word*/
#define OUT 0 /*outside a word*/

/*print input one word per line*/

int main(){
    int c , state;
    state = OUT;
    while((c = getchar()) != EOF){
        if(c == ' ' || c == '\n' || c == '\t'){
            if(state == IN){
                putchar('\n');
                state = OUT;
            }
        } else if(state == OUT){
            state = IN;
            putchar(c);
        } else {
            putchar(c);
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值