21xrx.com
2024-04-20 22:30:48 Saturday
登录
文章检索 我的文章 写文章
C程序,找出字符串中字符出现的频率
2021-07-07 10:03:29 深夜i     --     --
C

查找字符串中字符出现频率的 C 程序:该程序计算字符串中字符出现的频率,即哪个字符在字符串中出现了多少次。 例如,在字符串“code”中,每个字符“c”、“d”、“e”和“o”都出现了一次。 只考虑小写字母,忽略其他字符(大写和特殊字符)。 您可以修改此程序以处理大写和特殊符号。

 

C程序

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


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

   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') {
         x = string[c] - 'a';
         count[x]++;
      }

      c++;
   }

   for (c = 0; c < 26; c++)
         printf("%c occurs %d times in the string.\n", c + 'a', count[c]);

   return 0;
}

 

"count[string[c]-'a']++" 的解释,假设输入字符串以 'a' 开头,所以 c 最初是 0 并且 string[0] = 'a' 和 string[0] - 'a' = 0 并且我们增加 count[0],即 'a' 出现了一次并重复此操作直到扫描完整的字符串。

下载字符频率程序。

程序输出:

您是否注意到程序输出中的字符串至少包含每个字母表一次?

使用函数计算频率

我们将创建一个函数来计算输入字符串中字符的频率并将其打印在表格中(参见下面的输出图像)。

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


void find_frequency(char [], int []);
 
int main()
{
   char string[100];
   int c, count[26] = {0};
 
   printf("Input a string\n");
   gets(string);
 
   find_frequency(string, count);
   
   printf("Character Count\n");
   
   for (c = 0 ; c < 26 ; c++)
      printf("%c \t  %d\n", c + 'a', count[c]);
 
   return 0;
}

void find_frequency(char s[], int count[]) {
   int c = 0;
   
   while (s[c] != '\0') {
      if (s[c] >= 'a' && s[c] <= 'z' )
         count[s[c]-'a']++;
      c++;
   }
}

程序的输出:

我们不会将数组 count[] 的元素传递给函数 find_frequency 因为如果只考虑小写字母,它们将始终为 26。 但如果你愿意,你可以通过。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复
    相似文章