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

问题描述:

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

解题思路:

判断单词是否出现,可以用空格的出现来判断(连续的若干空格看做成一个),若当前字符为空格,表明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 = 0
	
	printf("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>      //gets

int 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;
}



  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值