我想计算字符串C程序中每个字母的出现频率或出现次数 [英] I want to count frequency or occurrence of a every letter in a string C program

查看:165
本文介绍了我想计算字符串C程序中每个字母的出现频率或出现次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我传递的字符串如"I am Programmer".

Suppose if I pass a string like "I am Programmer".

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

If a letter has occurred one time it should print "I has occurred 1 time", or else if a letter appears twice in the string it should print "a has occurred 2 times", "m has occurred 3 times" and so on for every letter in the string. I searched it and found in some website. Is there any way we could rewrite the code because I didn't understand the code.

#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] != '\0')
   {
      /** 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;
}

推荐答案

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

Ok here is the rewrite, the original code is better but this one might be easier to understand:

#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] != '\0')
   {
      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;
}

这篇关于我想计算字符串C程序中每个字母的出现频率或出现次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆