C语言统计单词数量程序 超详解

/*********************************************************************************************************************


Author:RainGiving
Date:2020-03-14
Description:一个统计单词个数的小程序


    1.我们选定一个文本中不常用的字符作为输入的末尾标记
    2.使用循环体+getchar()进行输入,通过检查换行字符统计行数
    3.一个单词一定是一个非空白字符开始,读到一个空白字符时结束
    4.用函数isspace()很方便地判断是否输入了空白字符,是空白字符isspace(c)为真;不是空白字符!isspace(c)为真
    5.设置一个上一个单词prev,用来判定最后一行是不是完整行
    6.下面说说识别单词的一种思路
        i.程序读入一个单词的首字符时把一个标记(inword)设置为1,然后递增单词计数,只要inword是1,后续单词都不计为单词开始
        ii.读到下一个空白字符,将inword设置为0,然后准备读取下一个单词

    1. We select an unusual character in the text as the end of the input
    2. Enter using the body of the loop +getchar() and count the number of lines by checking the newline characters
    A word must start with a non-whitespace character and end with a whitespace character
    4. The function isspace() is very convenient to determine whether a blank character is entered, and the blank character isspace(c) is true; Not white space! Isspace (c) is true
    5. Set the previous word prev to determine if the last line is complete
    6. Here is a way to recognize words
        i. When the program reads in the first character of a word, it sets a mark (inword) to 1, and then increments the word count. As long as the inword is 1, subsequent words are not counted as the beginning of the word
        ii. Read the next white space character, set inword to 0, and prepare to read the next word

    Powered by RainGiving 
    
************************************************************************************************************************/

#include<stdio.h>
#include<ctype.h>//提供isspace()函数
#include<stdbool.h>//提供bool,true,false定义
#define STOP '|'
int main(void)
{
    char c;//读入字符
    char prev;//读入的前一个字符
    long n_chars = 0L;//字符数
    int n_lines = 0;//行数
    int n_words = 0;//单词数
    int p_lines = 0;//不完整的行数
    bool inword = false;//c在单词里,则inword为true

    printf("Enter the text to be analyzed( | to be terminate):\n");
    prev = '\n';//用于识别完整的行
    while((c = getchar()) != STOP)
    {
        n_chars++;//统计字符
        if(c == '\n')
            n_lines++;//统计行
        if(!isspace(c) && !inword)//不是一个空白字符而且不在单词内,判定为一个新单词开始
        {
            inword = true;
            n_words++;//统计单词数
        }
        if(isspace(c) && inword)//是空白字符且之前应该在单词内,判定为一个单词结束
            inword = false;
        prev = c;//保存最后一次循环的字符,用来判定最后一行是否完整
    }

    if(prev != '\n')
        p_lines = 1;
    printf("character = %ld\nwords = %d\nlines = %d", n_chars, n_words, n_lines);

    return 0;
}
  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值