zoukankan      html  css  js  c++  java
  • 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 == '
    ' || c == '	')
                state = OUT;
            else if(state == OUT){
                state = IN;
                ++ nword;
            }
        }    // 可以用集合里的Vn图理解, 每次循环都有三种情况。
        printf("%d
    ", 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 '
    ':
                case '	':
                    nwhite ++;
                    break;
                default:
                    nother ++;
                    break;
            }
        }
        printf("digits =");
        for(i = 0; i < 10; i ++)
            printf(" %d", ndigit[i]);
        printf(", white space = %d, other = %d
    ", 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 != '
    ')
            s[i++] = c;
        if(c == '
    ')
            s[i++] = c;
        s[i] = '';
        return i;
    }
    
    int strindex(char s[], char t[])
    {
        int i, j, k;
        
        for(i = 0; s[i] != ''; i ++){
            for(j=i, k=0; t[k]!='' && s[j]==t[k]; j++, k++)
                ;
            if(k > 0 && t[k] == '')
                return i;
        }
        return -1;
    }

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

  • 相关阅读:
    Nginx编译安装
    Docker下mysql容器开启binlog日志(保留7天)
    podman
    error: audit:backlog limit exceeded
    64位win2003/win2008系统IIS6.0/7.5配置PHP的方法
    iis7.5安装配置php环境详细清晰教程,三步实现【图文】
    Windows下IIS+PHP 5.2的安装与配置
    无线路由MAC地址过滤安全可靠性讨论
    debian flam3 源码
    debian flam3 依赖文件
  • 原文地址:https://www.cnblogs.com/xkxf/p/6208289.html
Copyright © 2011-2022 走看看