简体   繁体   English

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

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

How to write below code in C? 如何在C中编写以下代码? Also: is there any built in function for checking length of an array? 另外:是否有任何内置函数可以检查数组的长度?

Python Code Python代码

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

if s in x:
  //Code

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
    }
}

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

There is a function for finding string length. 有一个用于查找字符串长度的函数。 It is strlen from string.h strlenstring.h

And then you could use the strcmp from the same header to compare strings, just as the other answers say. 然后,您可以使用同一标头中的strcmp来比较字符串,就像其他答案所说的那样。

A possible C implementation for Python's in method could be Python的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;
}

Note that the use of strncmp instead of strcmp allows for easier comparison of string with different sizes. 请注意,使用strncmp代替strcmp可以更轻松地比较不同大小的字符串。 More about the both of them in their manpage . 有关他们俩的更多信息,请参见联机帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM