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

规定:

单词的个数由空格出现的次数决定,连续的空格作为出现一次空格,一行开头的空格不统计在内。 如果测出某一字符为非空格,而它的前面的字符是空格,则表示“新的单词开始了“,此时使单词数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;
}

猜你喜欢

转载自blog.csdn.net/weixin_39916039/article/details/81509298