(篇九)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、参考结果:
统计单词

  • 32
    点赞
  • 150
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

鸿蒙Next

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值