Using the INSIDE function in C

Viewed 99

Small query: in Python, I know that you can check if char a is inside array b by saying:

 b = ['a', 'b', 'c', ...] # would be filled with letters
 if str(a) in b:
      # instructions.

Is there a similar operator or method for this in language C?

1 Answers

If the needle is a single char, then you can use either strchr or memchr. strchr only works if the haystack is null terminated, but you don't need to know the length in advance. memchr works even without a null terminator, but you do need to tell it the length. Examples of each:

#include <string.h>

char b1[] = { 'a', 'b', 'c' /* ... */, '\0' };
if(strchr(b1, a)) /* ... */;

char b2[] = { 'a', 'b', 'c' /* ... */ };
if(memchr(b2, a, sizeof b2)) /* ... */;

If the needle is an array of chars, then you can use strstr or memmem, with analogous differences. Examples of each:

#define _GNU_SOURCE
#include <string.h>

char b1[] = { 'a', 'b', 'c' /* ... */, '\0' };
if(strstr(b1, a)) /* ... */;

char b2[] = { 'a', 'b', 'c' /* ... */ };
if(memmem(b2, sizeof b2, a, sizeof a)) /* ... */;
Related