c语言期末复习题

代码参考:《K&R》

 

1、单词计数

#include<stdio.h>

#define IN 1
#define OUT 0

main()
{
    int c, state;
    int nword;

    nword = 0;
    state = OUT;
    while((c = getchar()) != EOF){
        if(c == ' ' || c == '\n' || c == '\t')
            state = OUT;
        else if(state == OUT){
            state = IN;
            ++ nword;
        }
    }    // 可以用集合里的Vn图理解, 每次循环都有三种情况。
    printf("%d\n", nword);
}

 

2、统计数字、空白符及其他字符

#include<stdio.h>

main()
{
    int c, i, nwhite, nother, ndigit[10];
    
    nwhite = nother;
    for(i = 0; i < 10; i ++)
        ndigit[i] = 0;
    while((c = getchar()) != EOF){
        switch(c){
            case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': 
                ndigit[c-'0'] ++;
                break;
            case ' ':
            case '\n':
            case '\t':
                nwhite ++;
                break;
            default:
                nother ++;
                break;
        }
    }
    printf("digits =");
    for(i = 0; i < 10; i ++)
        printf(" %d", ndigit[i]);
    printf(", white space = %d, other = %d\n", nwhite, nother);
    return 0;
}

 

3、找指定具有指定模式的行

#include<stdio.h>
#define MAXLINE 1000

int getline(char line[], int max);
int strindex(char source[], char searchfor[]);

char pattern[] = "ould";

main()
{
    char line[MAXLINE];
    int found = 0;
    
    while(getline(line , MAXLINE) > 0)
        if(strindex(line , pattern) >= 0){
            printf("%s", line);
            found++;
        }
    return found;
}

int getline(char s[], int lim)
{
    int c, i;
    
    i = 0;
    while(--lim > 0 && (c=getchar()) != EOF && c != '\n')
        s[i++] = c;
    if(c == '\n')
        s[i++] = c;
    s[i] = '\0';
    return i;
}

int strindex(char s[], char t[])
{
    int i, j, k;
    
    for(i = 0; s[i] != '\0'; i ++){
        for(j=i, k=0; t[k]!='\0' && s[j]==t[k]; j++, k++)
            ;
        if(k > 0 && t[k] == '\0')
            return i;
    }
    return -1;
}

实际在控制台界面运行时,是输入一行判断一行的,最后用Ctrl+Z结束。

posted @ 2016-12-21 16:57  xkfx  阅读(376)  评论(0编辑  收藏  举报