如何检查字符串是否在C中的字符串数组中?

Nak*_*kib 12 c arrays

如何用C写下面的代码?另外:是否有内置函数来检查数组的长度?

Python代码

x = ['ab', 'bc' , 'cd']
s = 'ab'

if s in x:
  //Code
Run Code Online (Sandbox Code Playgroud)

use*_*353 14

在C中没有用于检查数组长度的函数.但是,如果声明的数组与要检查的数组的范围相同,则可以执行以下操作

int len = sizeof(x)/sizeof(x[0]);
Run Code Online (Sandbox Code Playgroud)

你必须遍历x并对数组x的每个元素执行strcmp,以检查s是否与x的一个元素相同.

char * x [] = { "ab", "bc", "cd" };
char * s = "ab";
int len = sizeof(x)/sizeof(x[0]);
int i;

for(i = 0; i < len; ++i)
{
    if(!strcmp(x[i], s))
    {
        // Do your stuff
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 我没说你的帖子不正确; 事实并非如此.它只是比它本来的少,但是你修复了它.一切都很好,是吗?:-) (2认同)

nvl*_*ass 7

这样的事情?

#include <stdio.h>
#include <string.h>

int main() {
    char *x[] = {"ab", "bc", "cd", 0};
    char *s = "ab";
    int i = 0;
    while(x[i]) {
        if(strcmp(x[i], s) == 0) {
            printf("Gotcha!\n");
            break;
        }
        i++;
    }
}
Run Code Online (Sandbox Code Playgroud)