Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

arrays

c

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
like image 334
Nakib Avatar asked Dec 03 '12 05:12

Nakib


People also ask

How do you check if a string is present in array of strings?

You can use the includes() method in JavaScript to check if an item exists in an array. You can also use it to check if a substring exists within a string. It returns true if the item is found in the array/string and false if the item doesn't exist.

How do you check whether a string is in an array in 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.

How do you check if a value is an array of strings?

To check if a string is contained in an array, call the indexOf method, passing it the string as a parameter. The indexOf method returns the index of the first occurrence of the string in the array, or -1 if the string is not contained in the array.

Is a string in an array?

Strings are similar to arrays with just a few differences. Usually, the array size is fixed, while strings can have a variable number of elements. Arrays can contain any data type (char short int even other arrays) while strings are usually ASCII characters terminated with a NULL (0) character.


2 Answers

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
    }
}
like image 147
user93353 Avatar answered Oct 08 '22 20:10

user93353


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++;
    }
}
like image 26
nvlass Avatar answered Oct 08 '22 19:10

nvlass