(篇九)C语言统计某个字母的个数、统计各种字符的个数、统计单词的个数


本篇文章主要介绍在C语言中统计某个字母的个数、统计各种字符的个数和统计单词的个数;总之就是计数,-由于C语言中没有直接统计的函数,因此需要我们自己编写函数来循环遍历查找需要统计的元素。

一、统计某个字母的个数

1、参考代码:

#include <stdio.h>

int main()
{
	int i, k=0;  //i用于遍历 ,k用来计数 
	char a, aa[80];  //a是字符,aa是字符数组 
	printf("请输入一个字符串:\n");
	gets(aa);
	printf("请输入您需要统计的字符:\n"); 
	scanf("%c",&a);
	
	//开始统计字符个数
	for(i=1;aa[i];i++)
	{
		if(aa[i]==a)
		{
			k++;
		}
	}
	printf("%s中共有%d个%c",aa,k,a);
}

2、参考结果:
统计字母

二、统计各种字符的个数

1、普通ASCII码法:

#include <stdio.h>

int main()
{
	//普通ASCII码法:
	 char s[81];
	int i, letters=0, digit=0, space=0, others=0;
	puts("请输入一个字符串,长度不要超过80个字符:");
	gets(s); 
	for(i=0; s[i]!='\0'; i++)
	{
		if((s[i]>='A')&&(s[i]<='Z') || (s[i]>='a'&&s[i]<='z'))
			letters++;
		else if(s[i]>='0' && s[i]<='9')
			digit++;
		else if(s[i]== ' ')
			space++;
		else others++;
	}
	printf("字母:%d 数字:%d 空格:%d 其他:%d",letters,digit,space,others);
}

2、引用<ctype.h>库函数:

#include <stdio.h>
#include <ctype.h>

int main()
{ 
	//引用<ctype.h>库函数:
	char s[81];
	int i, letters=0, digit=0, space=0, others=0;
	puts("请输入一个字符串,长度不要超过80个字符:");
	gets(s); 
	for(i=0; s[i]!='\0'; i++)
	{
		if(isalpha(s[i]))
			letters++;
		else if(isdigit(s[i]))
			digit++;
		else if(isspace(s[i]))
			space++;
		else 
			others++;
	}
	printf("字母:%d 数字:%d 空格:%d 其他:%d",letters,digit,space,others);
}

参考结果:
统计各种字符

三、统计单词的个数

1、法一代码:

#include <stdio.h>
int wordcount(char *str);

void main()
{
	int n;
	char str[100];
	printf("请输入一句话(不超过99个单词):\n");
	gets(str);
	n= wordcount(str);
	printf("这句话中有%d个单词。",n);
} 

int wordcount(char *str)
{
	int n=0;
	int i;
	int isblank= 1;	//空字符
	for(i=0; str[i]!='\0'; i++) 
	{
		if(str[i]!=' ' && (str[i+1]==' ' || str[i+1]=='\0'))
		//s[i+1]为单词后的一个字符,若一个单词结束,其后一定是一个空格 
		{
			n++;
		} 
	}
	return n;
}

2、法二则是将if里面的内容换成以下:

		if(str[i] != ' ')		
		//此法为统计某字符本身不是空格且连续几个空格记为一个空格,得以统计单词个数 
		{
			if(isblank==1)
			{
				n++;
				isblank= 0;
			}
		}
		else					//若其本身是个空格,则不n++ 
		{
			isblank= 1;
		}

3、参考结果:
统计单词

猜你喜欢

转载自blog.csdn.net/Viewinfinitely/article/details/105332525