在 C 中计算字符串中大写和小写字母的程序

Program that counts Uppercase and Lowercase letters in a String in C

所以我想编写一个代码,您可以在其中找到字符串中大小写字母的数量(无空格) 所以我想要这样的东西:

input:
HEllO
Output:
2 3

所以我的代码是这样的:

#include<stdio.h>
int main() {
int upper = 0, lower = 0;
char ch[80];
int i;

printf("\nEnter The String : ");
gets(ch);

i = 0;
while (ch[i] != '') {
  if (ch[i] >= 'A' && ch[i] <= 'Z')
     upper++;
  if (ch[i] >= 'a' && ch[i] <= 'z')
     lower++;
  i++;
  }

  printf("%d %d", upper, lower);


  return (0);
  }

代码有问题,但找不到错误。有人可以修好吗?谢谢

更正代码-

#include <stdio.h>

int main(void)
{
    int upper = 0, lower = 0;
    char ch[80];
    int i = 0;
    printf("\nEnter The String : ");
    fgets(ch, sizeof(ch), stdin);
    while (ch[i] != '[=10=]')
    {
        if (ch[i] >= 'A' && ch[i] <= 'Z')
            upper++;
        if (ch[i] >= 'a' && ch[i] <= 'z')
            lower++;
        i++;
    }
    printf("\nuppercase letter(s): %d \nlowercase letter(s): %d", upper, lower);
    return 0;
}

注意: 我使用了 fgets() 而不是 gets(),因为后者存在缓冲区溢出问题。

问题是表达式“”。字符常量必须在单引号之间。在这种情况下,您想要测试字符串的结尾,因此您将使用空字符常量:'\0'.

#include <stdio.h>

int main(void) {
    int upper = 0, lower = 0;
    char ch[80];
    int i;

    printf("\nEnter The String : ");

    fgets(ch, sizeof(ch), stdin);
    i = 0;
    while (ch[i] != '[=10=]') {
        if (ch[i] >= 'A' && ch[i] <= 'Z')
            upper++;
        if (ch[i] >= 'a' && ch[i] <= 'z')
            lower++;
        i++;
    }

    printf("%d %d\n", upper, lower);

    return 0;
}

请注意,我还用 fgets 替换了 gets。你不应该使用 gets()。它不会传递缓冲区的长度,因此如果输入的长度超过 79 个字符,它将溢出 ch 数组,导致未定义的行为。 fgets 接受一个 size 参数并在读取到 size - 1 后停止读取。如果输入中存在换行符,它还会在结果字符串中包含换行符,而输入中没有换行符。

一种适用于所有输入长度的更好方法是一次读取一个字符的字符串,而不用费心存储它,因为您只关心上限和下限的计数。

#include <stdio.h>

int main(void) {
    unsigned upper = 0, lower = 0;
    printf("\nEnter The String : ");

    int c;
    while (EOF != (c = getchar())) {
        if ('\n' == c) break;

        if (c >= 'A' && c <= 'Z')
            upper++;
        if (c >= 'a' && c <= 'z')
            lower++;
    }
    printf("%u %u\n", upper, lower);

    return 0;
}   

在 C 中,字符串总是以 '[=10=]' 结尾。空字符串''和转义空字符不相同.

while (ch[i] != '') 应该是 while (ch[i] != '[=13=]')

你的程序应该可以运行了。