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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13677890/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 04:39:44  来源:igfitidea点击:

How to check if a string is in an array of strings in C?

carrays

提问by Nakib

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

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

Python Code

Python代码

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

if s in x:
  //Code

采纳答案by user93353

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

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

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

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.

您必须遍历 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
    }
}

回答by nvlass

Something like this??

这种东西??

#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++;
    }
}

回答by Matheus Santana

A possible C implementation for Python's inmethod could be

Pythonin方法的一个可能的 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;
}

Note that the use of strncmpinstead of strcmpallows for easier comparison of string with different sizes. More about the both of them in their manpage.

请注意,使用strncmp代替strcmp可以更轻松地比较不同大小的字符串。更多关于他们的信息在他们的手册

回答by Dimitar Slavchev

There is a function for finding string length. It is strlenfrom string.h

有一个用于查找字符串长度的函数。它strlen来自string.h

And then you could use the strcmpfrom the same header to compare strings, just as the other answers say.

然后您可以使用strcmp来自同一标题的 来比较字符串,就像其他答案所说的那样。