判断 char 是数字还是字母
如何确定 C 中的 char
(例如 a
或 9
)是数字还是字母?
使用: 还是这个更好
int a = Asc(theChar);
?
int a = (int)theChar
How do I determine if a char
in C such as a
or 9
is a number or a letter?
Is it better to use:
int a = Asc(theChar);
or this?
int a = (int)theChar
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
您需要在
中使用isalpha()
和isdigit()
标准函数。You'll want to use the
isalpha()
andisdigit()
standard functions in<ctype.h>
.字符只是整数,因此您实际上可以将字符与文字进行直接比较:
这适用于所有字符。 查看您的 ascii 表。
ctype.h 还提供了为您执行此操作的函数。
chars are just integers, so you can actually do a straight comparison of your character against literals:
This applies to all characters. See your ascii table.
ctype.h also provides functions to do this for you.
包含一系列用于确定char
表示字母还是数字的函数,例如isalpha
、>isdigit
和isalnum
。int a = (int)theChar
无法执行您想要的操作的原因是a
仅保存表示特定字符的整数值。例如,'9'
的 ASCII 数字是 57,'a'
的 ASCII 数字是 97。同样对于 ASCII:
if (theChar >= ' 0' && theChar <= '9')
if (theChar >= 'A' && theChar <= 'Z' || theChar >= 'a' && theChar <= 'z')
看一下 ASCII 表供您自己查看。
<ctype.h>
includes a range of functions for determining if achar
represents a letter or a number, such asisalpha
,isdigit
andisalnum
.The reason why
int a = (int)theChar
won't do what you want is becausea
will simply hold the integer value that represents a specific character. For example the ASCII number for'9'
is 57, and for'a'
it's 97.Also for ASCII:
if (theChar >= '0' && theChar <= '9')
if (theChar >= 'A' && theChar <= 'Z' || theChar >= 'a' && theChar <= 'z')
Take a look at an ASCII table to see for yourself.
这些都没有任何用处。使用标准库中的
isalpha()
或isdigit()
。它们位于
中。Neither of these does anything useful. Use
isalpha()
orisdigit()
from the standard library. They're in<ctype.h>
.通常,您可以使用简单的条件检查 ASCII 字母或数字
对于数字,您可以使用
But,因为 C 中的字符在内部被视为 ASCII 值 您也可以使用 ASCII 值来检查相同的内容。
如何检查字符是否为数字或字母
You can normally check for ASCII letters or numbers using simple conditions
For digits you can use
But since characters in C are internally treated as ASCII values you can also use ASCII values to check the same.
How to check if a character is number or letter
如果
(theChar >= '0' && theChar <='9')
它是一个数字。你明白了。If
(theChar >= '0' && theChar <='9')
it's a digit. You get the idea.c >= '0' && 上的 C99 标准c <= '9'
c >= '0' && c <= '9'
(在另一个答案中提到)有效,因为 C99 N1256 标准草案 5.2.1“字符集”说:但不保证 ASCII。
C99 standard on
c >= '0' && c <= '9'
c >= '0' && c <= '9'
(mentioned in another answer) works because C99 N1256 standard draft 5.2.1 "Character sets" says:ASCII is not guaranteed however.