在 C 中使用 INSIDE 函数

Jay*_*Roy 3 c arrays char

小查询:在 Python 中,我知道您可以通过以下方式检查 chara是否在数组内b

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

在 C 语言中是否有类似的运算符或方法?

Jos*_*ica 6

如果针是单针char,则可以使用strchrmemchrstrchr仅当 haystack 为空终止时才有效,但您不需要提前知道长度。memchr即使没有空终止符也能工作,但你确实需要告诉它长度。每个示例:

#include <string.h>

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

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

如果针是chars的数组,那么您可以使用strstrmemmem,具有类似的差异。每个示例:

#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)) /* ... */;
Run Code Online (Sandbox Code Playgroud)