简体   繁体   English

C标准库函数检查char *是否为单词?

[英]C standard library function to check if a char * is a word?

After reading in a line from a file and splitting that line into tokens, I need to check if the token only contains alphabetic characters [a-zA-Z]. 从文件中读取一行并将该行拆分为令牌后,我需要检查令牌是否仅包含字母字符[a-zA-Z]。 Is there some sort of function in the C Standard Library to check this? C标准库中是否有某种功能可以对此进行检查? I could use regex.h to check this but I think this is overblown. 我可以使用regex.h进行检查,但是我认为这已经过时了。

Sure, I could write a function that loops over the token and checks every char, but I don't want to reinvent the wheel. 当然,我可以编写一个遍历令牌并检查每个字符的函数,但我不想重蹈覆辙。

PS: Using a third party library is not an option. PS:不能选择使用第三方库。

Certainly: 当然:

#include <ctype.h>

int isalpha(int ch) // is alphabetic?
int isalnum(int ch) // is alphanumeric?

You have all these functions defined in ctype.h 您已经在ctype.h定义了所有这些功能

   int isalnum(int c);
   int isalpha(int c);
   int iscntrl(int c);
   int isdigit(int c);
   int isgraph(int c);
   int islower(int c);
   int isprint(int c);
   int ispunct(int c);
   int isspace(int c);
   int isupper(int c);
   int isxdigit(int c);

As stated by Kos, isalpha(int ch) and isalnum(int ch) , but those are not char* functions. 如Kos所述, isalpha(int ch)isalnum(int ch) ,但它们不是char *函数。 Coding your own with isalpha and is alnum should be quite easy, though you must be careful : if you are going to deal with special characters, check your locale (isalpha depends on them). 使用isalpha和alnum编码自己的代码应该很容易,尽管您必须小心:如果要处理特殊字符,请检查您的语言环境(isalpha取决于它们)。

Strspn will do the job. Strspn将完成这项工作。

The basic concept is that you give it a string, and returns the length of the longest piece that consists of characters in your specific list. 基本概念是给它一个字符串,并返回由特定列表中的字符组成的最长片段的长度。 add az and AZ to that list. 在该列表中添加az和AZ。 If the value back from strspn is the same as the strlen, you are good to go. 如果从strspn返回的值与strlen相同,则可以使用。

C Standard Library is very short on char* related functions. C标准库在与char *相关的​​功能上非常简短。 Please check this link to see if anythings helps: http://www.cplusplus.com/reference/clibrary/cstring/ 请检查此链接以查看是否有帮助: http : //www.cplusplus.com/reference/clibrary/cstring/

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

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