c - C语言计算字符串中大小写字母的程序

标签 c arrays string char int

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

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] != '\0')
    {
        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(),因为后者存在缓冲区溢出问题。

关于c - C语言计算字符串中大小写字母的程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33380592/

相关文章:

c# - 使用 array.sort 对数组进行排序

c - printf() 中的 e 格式和精度修饰符

c - Semmle QL : TaintTracking hasFlow() Problem with Sources that taint their Arguments

你能帮助改进我大学的一门低级软件和外围接口(interface)类(class)吗?

java - 列表 <Character> 上的 StringIndexOutOfBoundsException

c - 字符串序列分析器

c++ - 在C++中动态输入二维字符数组

c - 为什么当我们在下面的代码中逐行读取文件时程序会崩溃?

c - C (Arduino) 中的字符串数组(char 数组)。我如何完成它?

c - "Image reflecting"程序(不是实际图像,仅反射(reflect)用字符绘制的图画)