如何在C语言中编写下面的代码?此外,是否有内置函数可以检查数组长度?
Python 代码
x = ['ab', 'bc' , 'cd']
s = 'ab'
if s in x:
//Code
x = ['ab', 'bc' , 'cd']
s = 'ab'
if s in x:
//Code
C语言中没有检查数组长度的函数。但是,如果数组在你想要检查的同一范围内声明,可以采取以下方法:
int len = sizeof(x)/sizeof(x[0]);
你需要迭代数组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
}
}
像这样吗?
#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++;
}
}
in
方法的一个可能的C实现如下:#include <string.h>
int in(char **arr, int len, char *target) {
int i;
for(i = 0; i < len; i++) {
if(strncmp(arr[i], target, strlen(target)) == 0) {
return 1;
}
}
return 0;
}
int main() {
char *x[3] = { "ab", "bc", "cd" };
char *s = "ab";
if(in(x, 3, s)) {
// code
}
return 0;
}
strncmp
而不是strcmp
可以更容易地比较不同大小的字符串。有关它们的更多信息,请参阅它们的手册页。有一个用于查找字符串长度的函数。它是来自于 string.h
的 strlen
。
然后,您可以使用相同头文件中的 strcmp
来比较字符串,就像其他答案所说的那样。