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

时间:2022-07-24
本文章向大家介绍统计一行字符中有多少个单词,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
#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] != '')
	{
		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));
}