1. 程式人生 > >【C語言】統計一個字串中字母、數字、空格及其它字元的數量

【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);
}   

執行結果: