helpermethod
helpermethod

Reputation: 62234

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]. Is there some sort of function in the C Standard Library to check this? I could use regex.h to check this but I think this is overblown.

Sure, I could write a function that loops over the token and checks every char, but I don't want to reinvent the wheel.

P.S.: Using a third party library is not an option.

Upvotes: 0

Views: 583

Answers (5)

EvilTeach
EvilTeach

Reputation: 28872

Strspn will do the job.

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 a-z and A-Z to that list. If the value back from strspn is the same as the strlen, you are good to go.

Upvotes: 3

Raveline
Raveline

Reputation: 2678

As stated by Kos, isalpha(int ch) and isalnum(int ch), but those are not char* functions. 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).

Upvotes: 3

Didier Trosset
Didier Trosset

Reputation: 37467

You have all these functions defined in 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);

Upvotes: 3

Andrei Ciobanu
Andrei Ciobanu

Reputation: 12848

C Standard Library is very short on char* related functions. Please check this link to see if anythings helps: http://www.cplusplus.com/reference/clibrary/cstring/

Upvotes: -2

Kos
Kos

Reputation: 72279

Certainly:

#include <ctype.h>

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

Upvotes: 6

Related Questions