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

#include <stdio.h>

//只能是单词之间一个空格
int words(char string[])
{
	int result = 0, i = 0;
	
	while(string[i] != 0)
	{
		if(string[i++] == ' ')
		{
			result++;
		}
	}
	if(string[0] != 0)
		result++;

	return result;
}

//更加好
int words_2(char str[])
{
	int i = 0;
	int word = 0;
	int cnt = 0;

	while(str[i] != '\0')
	{
		if(str[i] == ' ')
			word = 0;
		else if(word == 0)
		{
			cnt++;
			word = 1;
		}
		i++;	
	}
	
	return cnt;
}


int main()
{
	char name[] = "liming  is good";
	printf("words of name is :%d \n", words(name));
	printf("words of name is :%d \n", words_2(name));
}

 

posted @ 2018-09-04 20:13  wdliming  阅读(187)  评论(0编辑  收藏  举报