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

后端 未结 4 647
北海茫月
北海茫月 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: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
        }
    }
    

提交回复
热议问题