19

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' , 'cd']
s = 'ab'

if s in x:
  //Code
Matheus Santana
  • 581
  • 1
  • 6
  • 22
Nakib
  • 4,593
  • 7
  • 23
  • 45

4 Answers4

18

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
    }
}
user93353
  • 13,733
  • 8
  • 60
  • 122
  • @CareyGregory - my original post wasn't incorrect - this way isn't a function. And it works only if the array is declared in the same scope. – user93353 Dec 03 '12 at 06:01
  • 2
    I didn't say your post was incorrect; it wasn't. It was simply less than it could have been, but you fixed it. So all is well, yes? :-) – Carey Gregory Dec 03 '12 at 06:05
  • This is not exactly what OP wants as the conditional code would execute multiple times if the target string appears more than once in the array of strings, right? – Matheus Santana Mar 21 '18 at 18:12
12

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++;
    }
}
Morgoth
  • 4,935
  • 8
  • 40
  • 66
nvlass
  • 665
  • 1
  • 6
  • 15
3

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.

Matheus Santana
  • 581
  • 1
  • 6
  • 22
1

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.

Dimitar Slavchev
  • 1,597
  • 3
  • 16
  • 20