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

时间:2015-10-27 23:56:46

标签: 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);
  }

代码有问题,但我找不到错误。有人可以解决吗?感谢。

3 个答案:

答案 0 :(得分:1)

更正代码 -

#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(),因为后者遇到了缓冲区溢出问题。

答案 1 :(得分:0)

问题在于表达&#39;。字符常量必须在单引号之间有一些东西。在这种情况下,您希望测试字符串的结尾,因此您将使用空字符常量:&#39; \ 0&#39;。

#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] != '\0') {
        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;
}   

答案 2 :(得分:0)

在C中,字符串始终以'\0'结尾。空字符串''和转义空字符不相同

while (ch[i] != '')应为while (ch[i] != '\0')

你的程序应该可以正常工作。

相关问题