2011-12-23 120 views

回答

71

你要使用isalpha()isdigit()標準功能<ctype.h>

char c = 'a'; // or whatever 

if (isalpha(c)) { 
    puts("it's a letter"); 
} else if (isdigit(c)) { 
    puts("it's a digit"); 
} else { 
    puts("something else?"); 
} 
10

這些都沒有任何用處。使用標準庫中的isalpha()isdigit()。他們在<ctype.h>

4

如果(theChar >= '0' && theChar <='9')這是一個數字。你明白了。

12

<ctype.h>包括一系列用於確定功能是否char代表一個字母或一個數字,如isalphaisdigitisalnum

int a = (int)theChar不會做你想做的事情的原因是因爲a只會保存代表特定字符的整數值。例如,對於'9'的ASCII號碼是57,而對於'a'它的97

也爲ASCII:

  • 數字 - if (theChar >= '0' && theChar <= '9')
  • 字母 -
    if (theChar >= 'A' && theChar <= 'Z' || theChar >= 'a' && theChar <= 'z')

看看一個ASCII table自己看看。

+1

爲「0」 <= X <校驗=「9」是所有符合標準的實現正確的(ASCII或不是不敬)。 C要求十進制數字具有連續的表示形式。至於信件,所有投注都關閉。 – Wiz 2015-01-22 00:50:03

+0

@很好! C99 5.2.1:http://stackoverflow.com/a/35936519/895245 – 2016-03-11 09:33:33

16

字符都只是整數,所以你實際上可以做你的性格對文字直比較:

if(c >= '0' && c <= '9'){ 

這適用於所有字符。 See your ascii table

ctype.h還提供了爲您做這個功能。

+0

這是正確的,但不能因爲ASCII得到保證,而且因爲數字的連續性的:http://stackoverflow.com/a/35936519/ 895245 – 2016-03-11 09:33:03

1

您可以正常查看使用簡單的條件

if((ch>='a' && ch<='z') || (ch>='A' && ch<='Z)) 
{ 
    /*This is an alphabet*/ 
} 

對於數字字母或數字,你可以使用

if(ch>='0' && ch<='9') 
{ 
    /*It is a digit*/ 
} 

但由於用C字符ASCII values在內部處理,您還可以使用ASCII值檢查相同。

How to check if a character is number or letter

1

C99標準c >= '0' && c <= '9'

c >= '0' && c <= '9'(提到in another answer)的作品,因爲C99 N1256 standard draft 5.2.1 「字符集」 說:

在源和執行基本特徵都在上面的十進制數字列表中,0之後的每個字符的值應該大於以前的價值。

ASCII但是不一定。

相關問題