C语言 统计字符出现的次数

2024-11-30 18:24:15
推荐回答(3个)
回答1:

#include

int main(void)
{
int num[10]={0};
int space=0,sels=0;
char ch;

while((ch=getchar())!=EOF)
{
if(ch>='0'&&ch<='9')
num[ch-'0']++;
else if(ch==' '||ch=='\t'||ch=='\n')
space++;
else
sels++;
}

for(ch=0;ch<10;ch++)
printf("%d ",num[ch]);
putchar('\n');

printf("%d\n",space);
printf("%d\n",sels);

return 0;
}

回答2:

#include
void main()
{ int num[10]={0},k=0,ech=0;
char str[100]="this is a test.27 276 \t \n ";
char *s=str;
while(*s)
{ if(*s>=48 && *s<=57) num[*s-48]++;
else if(*s==' ' || *s=='\t' || *s=='\n') k++;
else ech++;
s++;
}
for(int i=0;i<10;i++)
printf("%d ",num[i]);
printf("\n%d ",k);
printf("\n%d \n",ech);
}

回答3:

#include
#include
#define MAX_LENGTH 1000
void main()
{
int i;
int count[12] = {0,0,0,0,0,0,0,0,0,0,0,0};
char s[MAX_LENGTH];

scanf("%s\n", s);

for(i=0; i {
switch(s[i])
{
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
count[s[i]-30]++;
break;
case ' ': //
case '\n':
case ''\t:
count[10]++;
break;
default:
count[11]++;
break;
}
}
printf("\n");
for(i=0;i<10;i++)
{
printf("%d ", count[i]);
}
printf("\n%d", count[10]);
printf("\n%d", count[11]);
}