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

后端 未结 4 610
北海茫月
北海茫月 2021-01-01 19:06

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

Python Code

x = [\'ab\', \'bc\'          


        
相关标签:
4条回答
  • 2021-01-01 19:41

    A possible C implementation for Python's in method could be

    #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. More about the both of them in their manpage.

    0 讨论(0)
  • 2021-01-01 19:48

    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]);
    

    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
        }
    }
    
    0 讨论(0)
  • 2021-01-01 19:51

    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++;
        }
    }
    
    0 讨论(0)
  • 2021-01-01 20:03

    There is a function for finding string length. It is strlen from string.h

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

    0 讨论(0)
提交回复
热议问题