【C语言】统计一个字符串中字母、数字、空格及其它字符的数量

统计一个字符串中字母、数字、空格及其它字符的数量

解法1:

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

void Count(const char *str)
{
	int a=0,b=0,c=0,d=0;
	while(*str!='\0')
	{
		if((*str>='a'&&*str<='z')||(*str>='A'&&*str<='Z'))
		{
			a++;
		}
		else if(*str>='0'&&*str<='9')
		{
			b++;
		}
		else if(*str==' ')
		{
			c++;
		}
		else
		{
			d++;
		}
		str++;
	}
	printf("字母:%-4d  数字:%-4d  空格:%-4d  其他:%-4d\n",a,b,c,d);
}

int main()
{
	char a[100];
	printf("请输入一个字符串:");
	gets(a);
	Count(a);
}   

运行结果:

 在解法1中我们是通过if(*str>='a'&&*str<='z')||(*str>='A'&&*str<='Z')和if(*str>='0'&&*str<='9')两条语句分别判断*str是否是字母和数字,这样显得有些繁琐,且并非所有字符表的0~9数字是连续的。为了避免这些问题,其实可通过头文件<ctype.h>的函数来实现。

1、isdigit(int c)//判断是否为数字

【函数定义】int isdigit(int c)

【函数说明】该函数主要是识别参数是否为阿拉伯数字0~9。

【返回值】若参数c为数字,则返回TRUE,否则返回NULL(0)。

2、isalpha(int c)//判断是否为a~z A~Z

【函数定义】int isalpha(int c)

【函数说明】该函数主要是识别参数是否为阿拉伯数字0~9。

【返回值】若参数是字母字符,函数返回非零值,否则返回零值。

3、isalnum(int c)//判断是否是数字或a~z A~Z  
     相当于 isalpha(c) || isdigit(c),

【函数定义】int isalnum(int c);

【函数说明】该函数主要是识别参数是否为阿拉伯数字0~9或英文字符。

【返回值】若参数c 为字母或数字,若 c 为 0 ~ 9  a ~ z  A ~ Z 则返回非 0,否则返回 0。


引用头文件:#include <ctype.h>
注意,上述介绍的几个为宏定义,非真正函数

具体实现见解法2代码

解法2:

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

void Count(const char *str)
{
	int a=0,b=0,c=0,d=0;
	while(*str!='\0')
	{
		if(isalpha(*str))
		{
			a++;
		}
		else if(isdigit(*str))
		{
			b++;
		}
		else if(*str==' ')
		{
			c++;
		}
		else
		{
			d++;
		}
		str++;
	}
	printf("字母:%-4d  数字:%-4d  空格:%-4d  其他:%-4d\n",a,b,c,d);
}

int main()
{
	char a[100];
	printf("请输入一个字符串:");
	gets(a);
	Count(a);
}   

运行结果:

 

猜你喜欢

转载自blog.csdn.net/Jacky_Feng/article/details/83715162
今日推荐