简体   繁体   English

简单的方法来区分C中的数字和字母

[英]Easy way to differentiate between number and letter in C

I'm currently reading in a file, and storing that file into a cstring. 我正在读取文件,并将该文件存储到cstring中。 I'm using strtok to parse it out for the first few strings i'm interested in. After that, the substrings could be numbers (500,150,30) or character combinations( P(4),(K(5)). Is there an easy method in the string library to differentiate between numbers and letters? \\ 我正在使用strtok来解析我感兴趣的前几个字符串。之后,子字符串可以是数字(500,150,30)或字符组合(P(4),(K(5))。在字符串库中有一个简单的方法来区分数字和字母吗?

Thanks for the answers guys! 谢谢你们的答案!

If you are sure that there are no other symbols (@#$%^%&*^) you can use the isalpha() function. 如果您确定没有其他符号(@#$%^%&* ^),则可以使用isalpha()函数。

Usage: 用法:

   isalpha(p);// returns true if its alphabetic and false otherwise.

Also note that you should include ctype.h . 另请注意,您应该包含ctype.h

well, if you're reading a stream of bytes and want to differentiate between numbers and letters the following can be done: 好吧,如果您正在读取字节流并希望区分数字和字母,则可以执行以下操作:

// returns true if given char is a character, false otherwise
bool is_letter(char c) {
    return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
}

which is easy enough to implement where it is needed. 这很容易在需要的地方实现。 If you really want a library function, you can still use isalpha() or isdigit() from ctype.h , which basically should do the same thing. 如果你真的想要一个库函数,你仍然可以使用ctype.h isalpha()isdigit() ,它基本上应该做同样的事情。

NB: you might want to choose between bool or unsigned short . 注意:你可能想在boolunsigned short之间做出选择。 I won't enter into that debate . 我不会参加辩论

您可能会查找isalphaisdigit库函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM