用C语言编程:在显示器上输入一段字符串,并统计出现字符的个数和各个字符出现的次数

统计字母出现的个数和每个字母出现的次数

#include <stdio.h>
void main()
{
char c;
int i,letters=0,num[26]={0}; //字符的个数, 26个字符个数初始化为0
printf("请输入一段字符串:\n");
while((c=getchar())!='\n')
{
if(c>='a'&&c<='z'||c>='A'&&c<='Z')
{
letters++;
if(c>='a'&&c<='z') num[c-'a']++;
if(c>='A'&&c<='Z') num[c-'A']++;
}
}
printf("字符的个数:%d\n",letters);
printf("每个字符出现的次数:\n");
for(i=0;i<26;i++)
{
if(num[i]>0)
printf("字符%c:%d次 ",i+'a',num[i]);
}
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2011-10-22
#include <studio.h>
#include <string.h>
void frequency( string& s, char& A[ ], int& C[ ], int &k )
{
// s是输入字符串,数组A[ ]中记录字符串中有多少种不同的字符,C[ ]中记录每
//一种字符的出现次数。这两个数组都应在调用程序中定义。k返回不同字符数。
int i, j, len = s.length( );
if ( !len )
{
ptintf("The string is empty. " );
k = 0;
return;
}
else
{
A[0] = s[0]; C[0] = 1; k = 1; /*语句s[ i ]是串的操作*/
for ( i = 1; i < len; i++ ) C[ i ] = 0; /*初始化*/
for ( i = 1; i < len; i++ )
{ /*检测串中所有字符*/
j = 0;
while ( j < k && A[j] != s[ i] ) j++; /*检查s[ i]是否已在A[ ]中*/
if ( j == k )
{
A[k] = s[ i]; C[k]++; k++
} /*s[ i]从未检测过*/
else C[ j]++; /*s[ i]已经检测过*/
}
}
}
第2个回答  2011-10-22
#include<stdio.h>

struct Counter
{
int c;
int flag;
};
void main()
{
char a[50],b[50];
int i,j,sum;
struct Counter count[50]={0,0};
scanf("%s",a);
for(i=0;a[i]!=0;i++)
{
b[i]=a[i];
}
for(i=0;a[i]!=0;i++)
{
for(j=0;j<=i;j++)
{
if(a[i]==a[j]&&i!=j)
{
(count[j].c)++;
(count[j].flag)=1;
break;
}
else if(a[i]==a[j]&&i==j)
{
(count[i].c)=1;
(count[i].flag)=1;
}
}
}
sum=i;
printf("共有%d个字符\n",sum);
for(i=0;b[i]!=0;i++)
{
if(count[i].c!=0&&count[i].flag==1)
{
printf("%c有%d个\n",b[i],count[i].c);
}
}
}
第3个回答  2011-10-22
#include <stdio.h>

main()
{
int c,i,nwhite,nother;
int ndigit[10];

nwhite=nother=0;
for (i=0;i <10;++i)
ndigit[i]=0;

while ((c=getchar())!=EOF)

if (c> = '0 '&&c <= '9 ')
++ndigit[c- '0 '];
else if (c== ' '||c== '\n '||c== '\t ')
++nwhite;
else
++nother;

printf( "digit= ");
for (i=0;i <10;++i)
printf( "%d ",ndigit[i]);
printf( ".white space=%d,other=%d\n ",nwhite,nother);

}追问

你那能调试出来不呀

追答

追问

能不能弄个简单易懂的呀?

追答

#include

void count(char *s, int *digit, int *letter, int *other)
{
int i;
for(i=0;s[i]!='\0';i++)
{
if(s[i]>='a'&&s[i]='A'&&s[i]'0'&&s[i]<'9')
(*digit)++;
else
(*other)++;
}

}

void main()
{
int x=0,y=0,z=0;
char ch[80];
printf("Enter a string:");
gets(ch);
count(ch,&x,&y,&z);
printf("数字有:%d个,字母有:%d个,其它符号有:%d个\n",x,y,z);
}这个够简单了吧

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网