In C - check if a char exists in a char array In C - check if a char exists in a char array arrays arrays

In C - check if a char exists in a char array


The less well-known but extremely useful (and standard since C89 — meaning 'forever') functions in the C library provide the information in a single call. Actually, there are multiple functions — an embarrassment of riches. The relevant ones for this are:

7.21.5.3 The strcspn function

Synopsis

#include <string.h>size_t strcspn(const char *s1, const char *s2);

Description

The strcspn function computes the length of the maximum initial segment of the string pointed to by s1 which consists entirely of characters not from the string pointed to by s2.

Returns

The strcspn function returns the length of the segment.

7.21.5.4 The strpbrk function

Synopsis

#include <string.h>char *strpbrk(const char *s1, const char *s2);

Description

The strpbrk function locates the first occurrence in the string pointed to by s1 of any character from the string pointed to by s2.

Returns

The strpbrk function returns a pointer to the character, or a null pointer if no character from s2 occurs in s1.

The question asks about 'for each char in string ... if it is in list of invalid chars'.

With these functions, you can write:

size_t len = strlen(test);size_t spn = strcspn(test, "invald");if (spn != len) { ...there's a problem... }

Or:

if (strpbrk(test, "invald") != 0) { ...there's a problem... }

Which is better depends on what else you want to do. There is also the related strspn() function which is sometimes useful (whitelist instead of blacklist).


The equivalent C code looks like this:

#include <stdio.h>#include <string.h>// This code outputs: h is in "This is my test string"int main(int argc, char* argv[]){   const char *invalid_characters = "hz";   char *mystring = "This is my test string";   char *c = mystring;   while (*c)   {       if (strchr(invalid_characters, *c))       {          printf("%c is in \"%s\"\n", *c, mystring);       }       c++;   }   return 0;}

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:

#include <string.h>char* foo = "abcdefghijkl";if (strchr(foo, 'a') != NULL){  // do stuff}

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:

#include <string.h>char foo[] = { 'a', 'b', 'c', 'd', 'e' }; // note last element isn't '\0'if (memchr(foo, 'a', sizeof(foo))){  // do stuff}