如何用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)
这样的事情?
#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)