I'm trying to check if a character belongs to a list/array of invalid characters.
Coming from a Python background, I used to be able to just say :
for c in string:
if c in invalid_characters:
#do stuff, etc
How can I do this with regular C char arrays?
strchr for searching a char from start (strrchr from the end):
The equivalent C code looks like this:
Note that invalid_characters is a C string, ie. a null-terminated
char
array.Assuming your input is a standard null-terminated C string, you want to use
strchr
:If on the other hand your array is not null-terminated (i.e. just raw data), you'll need to use
memchr
and provide a size:I believe the original question said:
and not:
which, if it did, then
strchr
would indeed be the most suitable answer. If, however, there is no null termination to an array of chars or if the chars are in a list structure, then you will need to either create a null-terminated string and usestrchr
or manually iterate over the elements in the collection, checking each in turn. If the collection is small, then a linear search will be fine. A large collection may need a more suitable structure to improve the search times - a sorted array or a balanced binary tree for example.Pick whatever works best for you situation.
You want
If the character c is in the string s it returns a pointer to the location in s. Otherwise it returns NULL. So just use your list of invalid characters as the string.
use strchr function when dealing with C strings.
Here is an example of what you want to do.
Use memchr when dealing with memory blocks (as not null terminated arrays)
http://www.cplusplus.com/reference/clibrary/cstring/memchr/
http://www.cplusplus.com/reference/clibrary/cstring/strchr/