如何編寫C語言程序判斷一個字符是否是字母或數字

怎樣判斷一個字符是否是一個字母?

字母表中的所有字母(包括計算機鍵盤上的所有鍵)都被賦予了一個值,這些字符及其相應的值一起組成了ASCII字符集,該字符集在北美、歐洲和許多講英語的國家中得到了廣泛的使用。

字母字符被分成大寫和小寫兩組,並按數字順序排列。有了這種安排,就能很方便地檢查一個字符是否是一個字母以及是大寫還是小寫。下面這段代碼說明了如何檢查一個字符是否是一個字母:
int ch ;
ch=getche() ;
if((ch>=97) && (ch<=122))
      printf(" %c is a lowercase letter\n" ,ch);
else if ((ch>=65) && (ch<=90))
      print(" %c is an uppercase letter\n" ,ch);
else
      printf(" %c is not an alphabet letter\n" ,ch) ;

在上例中,變量ch的值與十進制值進行比較。當然,它也可以與字符本身進行比較,因爲ASCII字符既是按字符順序定義的,也是按數字順序定義的。請看下例:
int ch ;
ch=getche() ;
if((ch>='a') && (ch<='z'))
      printf("%c is a lowercase letter\n" ,ch);
else if ((ch>='A') && (ch<='Z'))
      print(" %c is a uppercase letter\n" ,ch);
else
      printf(" %c is not an alphabet letter\n" ,ch);
你可以隨便選擇一種方法在程序中使用。但是,後一種方法的可讀性要好一些,因爲你很難記住ASCII碼錶中每個字符所對應的十進制值。

怎樣判斷一個字符是否是一個數字?

在ASCII碼錶中,數字字符所對應的十進制值在48到57這個範圍之內,因此,你可以用如下所示的代碼來檢查一個字符是否是一個數字:
int ch ;
ch=getche() ;
if((ch>=48) && (ch<=57))       
      printf(" %c is a number character between 0 and 9\n" ,ch) ;
else
      printf(" %c is not a number\n" ,ch) ;

與20.18相似,變量ch也可以和數字本身進行比較:
int ch ;
ch=getche () ;
if((ch>='O') && (ch<='9'))
      printf(" %c is a number character between 0 and 9\n" ,oh) ;
else
      printf(" %c is not a number~n" ,ch) ;
同樣,選用哪一種方法由你決定,但後一種方法可讀性更強。

發佈了48 篇原創文章 · 獲贊 9 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章