简体   繁体   中英

search and compare a string with an array of strings

This is the code I have

const char *s[5];={"abcd","efgh","ijkl","mnop","qrst"};
char a[4];
while (1)
      {
      scanf("%4s",&a);

      //compare a with s array

      if(/*a exists in s*/)
      printf("it is ok");

      if(/*a does not exist in s*/)
      printf("it is not ok");
}

For example when I type "dcba" I want to see "it is not ok". When I type "efgh" I want to see "it is ok".

First declare your arrays a as

char a[5];

use fgets to input string (do not use scanf ), then use strcmp or strncmp function to compare the two string/(literals).

If you were using C++ and the std::string class, you could use a std::vector<string> and the std::find from <algorithm> and find your string.

Since you are using C-style strings, search your reference book for strcmp for comparing an item in the container with a C-style string variable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM