本篇文章主要介紹在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、參考結果: