簡體   English   中英

C - 想要使用符號轉換小寫和大寫字母

[英]C - Want to convert lowercase and uppercase letters using symbols

我希望在C中將小寫字母轉換為大寫字母,反之亦然。我已經這樣做但是當我使用像'_'或'。'這樣的符號時。 或','....在輸入中我在輸出上得到隨機字符,就像方格內的問號。

輸入:AAbb
輸出:aaBB
輸入:a_A
輸出:A⍰a

如何使用符號進行此操作?

碼:

#include <stdio.h>

int main(void)
{
    char a[50];
    int x = 1;

    while( x > 0){
        gets(a);
        int i,length=0;
        for(i=0;a[i]!='\0';i++)
            length+=1;
        for(i=0;i<length;i++){
            a[i]=a[i]^32;
        }
        printf("%s",&a);
    }
}

不要改變任何你不想改變的東西。

替換:

a[i]=a[i]^32;

if (a[i] >= 'A' && a[i] <= 'Z' ||
    a[i] >= 'a' && a[i] <= 'z')
{
    a[i] = a[i] ^ 32;
}

如果你#include <ctype.h>你可以這樣做:

a[i] = islower(a[i]) ? toupper(a[i])
                     : tolower(a[i]);

...使用符號轉換小寫和大寫字母
...當我使用像'_'或'。'這樣的符號時 或','....在輸入上我得到隨機字符

使用isupper()tolower()toupper() 這是切換案例的標准且高度便攜的方式。 考慮在各種平台上有超過26個字母。

#include <ctype.h>
#include <stdio.h>

int main(void ){
  char a[50];
  {
    gets(a);   // dubious, consider fgets().
    int i,length=0;

    for(i=0;a[i];i++){
      unsigned char ch = a[i];
      if (isupper(ch) {
        a[i]= tolower(ch);
      } else {
        a[i]= toupper(ch);
      }
    }
    printf("%s",a);  // use `a` , not `&a`
  }
}

如果代碼想要在不使用標准函數的情況下切換大小寫,並且知道char是一個字母,則代碼可以使用以下代碼。 它合理地假設AZ和az相差一位,如ASCIIEBCDIC中的情況

        // Avoid magic numbers like 32
        a[i] ^= 'a' ^ 'A';

仍建議使用標准功能。

C標准指定<ctype.h>函數來處理基本字符集的大小寫:

  • islower(c)測試字符是否為小寫
  • isupper(c)測試字符是否為大寫
  • tolower(c)將任何字符轉換為小寫字母
  • toupper(c)將任何字符轉換為大寫字母

以下是如何使用這些:

#include <ctype.h>
#include <stdio.h>

int main(void) {
    char a[50];

    if (fgets(a, sizeof a, stdin)) {
        int i;
        for (i = 0; a[i] != '\0'; i++) {
            unsigned char c = a[i];
            a[i] = islower(c) ? toupper(c) : tolower(c);
        }
        printf("%s", a);
    }
    return 0;
}

你不能。 見ascii表。 與小寫字母的大寫字母不同的是位5 00100000b,其等效於十進制為32.但這僅適用於字母。

你應該把ifs用來處理任何不是字母的東西。

暫無
暫無

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

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