我编写了一个程序来计算用户输入的字符串中的字符频率。它为所有小写字母提供正确的输出,但不适用于大写字母。我无法在代码中找到问题:
#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;
}
请帮忙!
这是屏幕截图。希望您能理解我面临的问题:
不计算大写字母。
最佳答案
我能看到的唯一问题是边界...
编辑
这可以完全跳过,因为 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/