C语言循环+数组 该如何写

从终端输入一串字符,统计字符串中每个字母出现的次数。

提示:

用一个26个元素的数组,如num[26], 表示计数。num[0]存放a的个数, num[1]存放b的个数…。这样对每一个字符不必用switch,而只需用一个简单的计算:
++num[toupper(ch) - ’A’]就可以了。

解答如下,回车键结束输入

img

#include <stdio.h>
#include <ctype.h>
int main()
{
    int num[26]={0};
    char ch=' ';
    while((ch=getwchar())!='\n')
    {
            ++num[toupper(ch) - 'A'];
    }
    for(int i=0;i<26 ;i++ )
    {
        printf("%c  %d\n",i+'A',num[i]);
    }
    return 0;
}
#include <stdio.h>
#include <stdlib.h>

void main()
{
    //声明接收字符串的数组
    char str[26];
    //声明统计次数的数组
    int count[26] = {0};
    int count1[26] = {0};
    int i,j;
    for(i = 0;i < 26;i++)
    {
        scanf("%c",&str[i]);
    }
    //for循环统计次数
    for(i = 0;i < 26; i++)
    {
        int number = str[i] - 'a';
        //统计字符出现的次数
        count[number] += 1;
    }
    for(i = 0;i < 26;i++)
    {
        if (count[i] > 0)
        {
            printf("%c出现了%d次\n", 'a' + i, count[i]);
        }
    }
    
    for(j = 0;j < 26; j++)
    {
        int number = 0;//前面用过,现在初始化为 0 
        number = str[j] - 'A';
        //统计字符出现的次数
        count1[number] += 1;
    }
    for(j = 0;j < 26;j++)
    {
        if (count1[j] > 0)
        {
            printf("%c出现了%d次\n", 'A' + j, count1[j]);
        }
    }
}

img

你没说是否区分大小写啊,以及输入其它字符吗?。都是大写字母吗?
大概如此:

#include<iostream>
using namespace std;

int main()
{
    int numA[26] = {0},numa[26] = {0},i=0;
    char s[10001];
    cin.getline(s,10001);
    while(s[i] != '\0')
    {
        if(s[i] >= 'a' && s[i] <= 'z') 
            ++numa[s[i] - 'a'];
        else if(s[i] >= 'A' && s[i] <= 'Z') 
            ++numA[s[i] - 'A'];
        i++;
    }
    for(i=0;i<26;i++)
    {
        if(numA[i] > 0)
        {
            cout<<char('A'+i)<<":"<<numA[i]<<endl;
        }
    }
    for(i=0;i<26;i++)
    {
        if(numa[i] > 0)
        {
            cout<<char('a'+i)<<":"<<numa[i]<<endl;
        }
    }
    return 0;
}

#include <ctype.h>
#include <stdio.h>

int main() {
  int ch, num[256] = {0};
  while (((ch = getchar()) != EOF) && ch != '\n')
    num[ch]++;
  for (int i = 0; i < 256; i++)
    if (num[i] > 0)
      printf("%#x %c %d\n", i, isprint(i) ? i : ' ', num[i]);
  return 0;
}
$ gcc -Wall main.cpp
$ ./a.out
Hello, world!
0x20   1
0x21 ! 1
0x2c , 1
0x48 H 1
0x64 d 1
0x65 e 1
0x6c l 3
0x6f o 2
0x72 r 1
0x77 w 1