[英]Why is my code only counting the frequency of lower case letters from my string
我正在开发一个计算字符串中字符数的程序。 它还计算并报告每个字母 (az) 的使用次数。 由于我无法弄清楚我的程序只会计算并返回小写字母的原因。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char string[100];
int c = 0, count[26] = {0}, x, charcount = 0;
printf("Enter a string\n");
gets(string);
while (string[c] != '\0')
{
if (string[c] >= 'a'||'A' && string[c] <= 'z'||'Z')
{
x = string[c] - 'a';
count[x]++;
}
c++;
}
for(c = 0; c < strlen(string); c++)
{
if(string[c] !=' ')
{
charcount++;
}
}
printf("The string %s is %d characters long.\n", string, charcount);
for (c = 0; c < 26; c++)
{
if(count[c] != 0)
printf("%c %d \n", c + 'A', count[c]);
}
return 0;
}
有人知道我在这里做错了什么吗?
这个:
if (string[c] >= 'a'||'A' && string[c] <= 'z'||'Z')
不起作用。 我不会试图解释这实际上在做什么,但足以说明这不是你的意思。
在 C 中,您需要一次执行一个逻辑运算,然后对结果执行另一个逻辑运算。
这就是你的意思:
if ((string[c] >= 'a' && string[c] <= 'z') || (string[c] >= 'A' && string[c] <= 'Z'))
可以使用ctype.h
库中的tolower
(或toupper
) function 来简化:
#include <ctype.h>
//...
if (tolower(string[c]) >= 'a' && tolower(string[c]) <= 'z')
或者更好的是,只需使用ctype.h
库中的isalpha
function 来验证字符是否为字母:
#include <ctype.h>
//...
if (isalpha(string[c]))
这里还有另一个问题:
x = string[c] - 'a';
在减去“a”之前,您需要将字母转换为小写,所以我们可以再次使用tolower
:
x = tolower(string[c]) - 'a';
您的这行代码严重损坏:
if (string[c] >= 'a'||'A' && string[c] <= 'z'||'Z')
如果应该是:
if ( ((string[c] >= 'a') && (string[c] <= 'z')) || ((string[c] >= 'A') && (string[c] <= 'Z'))
但是整个混乱可以替换为:
#include <ctype.h>
....
if (isalpha(string[c]))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.