簡體   English   中英

計算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] != '\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()因為后者存在緩沖區溢出問題。

問題是表達式''。 字符常量必須在單引號之間有一些東西。 在這種情況下,您想要測試字符串的結尾,因此您將使用空字符常量:'\\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] != '\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 替換了 get。 你永遠不應該使用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 中,字符串總是以'\\0'結尾。 空字符串''和轉義空字符不相同

while (ch[i] != '')應該是while (ch[i] != '\\0')

你的程序應該可以工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM