输入一行字符,统计其中有多少单词,单词之间用空格隔开

来源:互联网 发布:淘宝董事长 编辑:程序博客网 时间:2024/05/27 14:14

问题描述:

  输入一行字符,统计其中有多少单词,单词之间用空格隔开

解题思路:

判断单词是否出现,可以用空格的出现来判断(连续的若干空格看做成一个),若当前字符为空格,表明word未出现,当前字符非空格,之前字符为空格表明新单词出现,count++,之前字符是否为空格,用状态标志位word来标记

代码如下:

#include<stdio.h>   //printf#include<string.h>  //gets#include<stdlib.h>  //system#define MAXLENTH 1000 //字符数组的最大容量int main(){system("title count the number of 9");//设置cmd窗口标题system("mode con cols=100 lines=100");//设置窗口宽度和高度system("color 0A");                   //设置幕布和字体颜色char string[MAXLENTH];//存放终端输入的一段字符char *ch = string;    //指向该数组int count = 0;        //统计单词个数int word = 0;         //状态标志位,出现新单词(当前字符非空格,之前字符为空格)word=1,否则word = 0printf("please input the charactors you want to count the words:\n");gets(string);for(;*ch != '\0';++ch){if(*ch == ' ')    //当前字符为‘空格’,表明新单词未出现{word = 0;}else if(word == 0)//(当前字符非空格,之前字符为空格)word=1{count++;word = 1;}}printf("there are %d words\n",count);return 0;}


也可以不用指针,代码如下:

#include<stdio.h>       //printf#include<stdlib.h>      //system#include<string.h>      //getsint main(){system("mode con cols=100 lines=100");system("color 0A");char string[100000];//存放一段字符int num = 0;        //统计单词个数int word = 0;       //单词是否出现的标志,0:新单词未出现,1:新单词出现int i;printf("please input the charactors that you want to count words:\n");gets(string);       //从终端输入想要统计单词个数的一段字符for(i=0;string[i] != '\0';++i){if(string[i] == ' ')//当前字符是空格,表示新单词未出现word = 0{word = 0;}else if(word == 0)  //当前字符不是空格并且前一个字符是空格,表示新单词出现{word = 1;num++;}}printf("there are %d words in the charactors you put \n",num);system("pause");return 0;}



1 0
原创粉丝点击