我想计算字符串 C 程序中每个字母的频率或出现次数

I want to count frequency or occurrence of a every letter in a string C program

假设我传递一个像 "I am Programmer".

这样的字符串

如果一个字母出现一次,它应该打印 "I has occurred 1 time",否则如果一个字母在字符串中出现两次,它应该打印 "a has occurred 2 times""m has occurred 3 times" 等等字符串中的字母。我搜索了一下,在某个网站上找到了。有没有什么办法可以重写代码,因为我看不懂代码。

#include <stdio.h>
#include <string.h>

int main()
{
   char string[100];
   int c = 0, count[26] = {0};

   printf("Enter a string\n");
   gets(string);

   while (string[c] != '[=10=]')
   {
      /** Considering characters from 'a' to 'z' only
          and ignoring others */

      if (string[c] >= 'a' && string[c] <= 'z') 
         count[string[c]-'a']++;

      c++;
   }

   for (c = 0; c < 26; c++)
   {
      /** Printing only those characters 
          whose count is at least 1 */

      if (count[c] != 0)
         printf("%c occurs %d times in the entered string.\n",c+'a',count[c]);
   }

   return 0;
}

一个变量类型 char 可以被认为是一个整数(无论如何它们是如何存储在内存中的)所以你可以写:

int test = 'a';
printf("%i", test);

它会打印你 97。此外,从 a 到 z 的字母由连续整数表示,这意味着 'b' = 98。因此 taht 也意味着 'b' - 'a' = 1

在您的解决方案中,他们创建了一个包含 26 个整数的数组来计算每个字母在 'a' 和 'z' 之间出现的次数(请注意,他们这样做会忽略所有其他字母,包括 A-Z)

他们决定在数组 count 中,索引 0 在这里计算 a 的出现次数,1 代表 b .... 25 代表 z,这解释了这一点:

count[string[c]-'a']++;

如果 string[c]b 那么 string[c]-'a' = 1 所以我们有计数数组的索引并增加 b.

的出现次数

所以你只需要理解这段代码就可以基本上像操作 int 一样操作 char,你还应该快速搜索一下什么是 ASCII 码。

如果您仍然需要重写此代码才能理解,请告诉我。

好的,这里是重写,原始代码更好,但这个可能更容易理解:

#include <stdio.h>
#include <string.h>

int main()
{
   char cur_char;
   char string[100];
   int index = 0, count[255] = {0};

   printf("Enter a string\n");
   gets(string);


   while (string[index] != '[=10=]')
   {
      char cur_char = string[index];

      // cur_char is a char but it acts as the index of the array like
      // if it was an unsigned short
      count[cur_char] = count[cur_char] + 1;

      index++;
   }

   for (index = 0; index < 255; index++)
   {
      if (count[index] != 0)
         printf("%c occurs %d times in the entered string.\n", index, count[index]);
   }

   return 0;
}