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
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.
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.
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.
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.
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
}
}
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++;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With