字符串-----统计一行字符中有多少个单词

规定:

单词的个数由空格出现的次数决定,连续的空格作为出现一次空格,一行开头的空格不统计在内。 如果测出某一字符为非空格,而它的前面的字符是空格,则表示“新的单词开始了“,此时使单词数count累加1。 如果当前字符为非空格,而其前面的字符也是非空格,则意味着仍然是原来那个单词的继续,count不应再累加1。 添加一个标志word,用来标识当前字符的前一个字符是否为空格;若word等于0,则表示前一个字符是空格;若word等于1,则表示前一个字符为非空格。

普通方法:

#include <iostream>
using namespace std;
#define MAXSIZE 1024

int main() 
{

	char string[MAXSIZE];
	//cin.getline接受两个对象,一个是对象地址,一个是字符个数
	cin.getline(string, MAXSIZE);
	int count = 0;
	int word = 0;
	for (int i = 0; string[i] != '\0'; i++)
	{
		if (string[i] == ' ')
			word = 0;
		else if (word == 0)
		{
			word = 1;
			count++;
		}
	}
	printf("%d\n", count);
	return 0;
}

指针方法:

#include <iostream>
using namespace std;
#define MAXSIZE 1024

int main(int argc, const char * argv[]) {

	char string[MAXSIZE];
//cin.getline接受两个对象,一个是对象地址,一个是字符个数
	cin.getline(string, MAXSIZE);
	int count = 0;
	int word = 0;
//定义一个指向string的指针
	char *p = string;
//当字符串不等于'\0'时
	while (*p != '\0')
	{
		if (*p == ' ')
			word = 0;
		else if (word == 0)
		{
			++count;
			word = 1;
		}
		++p;
	}
	printf("%d\n", count);
	return 0;
}

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值