#include<stdio.h>
#include<stdlib.h>
int main()
{
char c
int letters=0
int space=0
int digit=0
int other=0
printf("请输入一行字符:>")
while((c=getchar())!='\n')
{
if((c>='a'&&c<='z')||(c>='A'&&c<='Z'))
{
letters++
}
else if(''==c)
{
space++
}
else if(c>='0'&&c<='9')
{
digit++
}
else
{
other++
}
}
printf("字母的个数:>%d\n空格的个数:>%d\
\n数字的个数:>%d\n其他字符的个数:>%d\n",\
letters,space,digit,other)
system("pause")
return 0
}
我们进行程序编写的时候,经常会遇到统计字符串中各个字符个数的需求。那么如何实现这种功能呢?下面我给大家分享一下。
工具/材料Visual Studio 2015
01首先打开Visual Studio软件,新建一个Win32应用程序,并且在项目下新建C语言文件,如下图所示
02然后我们在C语言文件中导入程序要用到的库文件,如下图所示
03接下来我们就开始实现字符统计的功能,主要是挨个读取字符串中的字符,然后判断字符的类别,如下图所示
04最后我们运行程序,输入一个字符以后,你就会发现程序已经自动统计好了各种字符的个数了,如下图所示
原发布者:zlaikai1314#include#include#include#includeusingnamespacestdchara[100]//字符数组intb[100]//字符个数doublep_a[100]//字符概率数组intsum=0//字符总数//判断当前字符temp是否已出现过boolsearch(chartemp,chara[],intm,intn)//m为数组a的元素总个数,即100;n为当前数组a中存放的字符种类的个数{inti=0while(i<n){if(a[i]==temp)returntrueelsei++}returnfalse}//求各个字符的个数,放在数组b中voidread_file(stringfile_name="test_data.txt"){intk=0ifstreamfile(file_name.c_str())//将string转化为char数组chartempif(file.is_open()==true)//检查文件是否打开{while(file.peek()!=EOF)//从文件中读取一个字符,但该字符并未从输入流中删除{file.get(temp)//从文件读入一个字符并把它存储在tempsum++//统计出现的字符总数if(search(temp,a,100,k)){for(inti=0i<ki++){if(temp==a[i]){b[i]++break}}}else