如何检查字符串是否在C中的字符串数组中? [英] How to check if a string is in an array of strings in C?

查看:847
本文介绍了如何检查字符串是否在C中的字符串数组中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何用C语言编写以下代码?另外:是否有内置函数可以检查数组的长度?

How to write below code in C? Also: is there any built in function for checking length of an array?

Python代码

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

if s in x:
  //Code

推荐答案

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

There is no function for checking length of array in C. However, if the array is declared in the same scope as where you want to check, you can do the following

int len = sizeof(x)/sizeof(x[0]);

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

You have to iterate through x and do strcmp on each element of array x, to check if s is the same as one of the elements of 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
    }
}

这篇关于如何检查字符串是否在C中的字符串数组中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆