使用 C 计算字符串中的字符频率

标签 c

我编写了一个程序来计算用户输入的字符串中的字符频率。它为所有小写字母提供正确的输出,但不适用于大写字母。我无法在代码中找到问题:

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

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

   printf("Enter a string\n");
   fgets(string,100,stdin);

   while(string[c] != '\n') {
      c++;
   }
   string[c] = '\0';
   c = 0;

   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']++;
      else 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;
}

请帮忙!

这是屏幕截图。希望您能理解我面临的问题:

enter image description here

不计算大写字母。

最佳答案

我能看到的唯一问题是边界...

编辑

这可以完全跳过,因为 fgets() 确保尾随 '\0' 并且您稍后可以优雅地处理 '\n'你的支票。

while(string[c] != '\n') {
    c++;
}
string[c] = '\0';

要删除它应该是的'\n'

while(string[c] && string[c] != '\n') {
   c++;
}
string[c] = '\0';

while (string[c] != '\0')

由于 fgets() 的语义而很好。

关于使用 C 计算字符串中的字符频率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36892298/

相关文章:

c - 从文件崩溃读取时使用 realloc 扩展缓冲区

c++ - _splitpath_s : wrong argument type?

php - 其他语言上的 C 指针等效项

c - 如何在不限制堆栈的情况下限制使用 `malloc()` 获取的内存?

c - 列出所有线程

c - 宏初始化不清楚

C:暂停 system() 调用

c - 自定义库的常用位置

C 指针数组地址分配

c++ - Linux 编程接口(interface)中的信号处理程序示例