简体   繁体   English

搜索字符串并将其与字符串数组进行比较

[英]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". 例如,当我键入“ dcba”时,我想看到“它不正常”。 When I type "efgh" I want to see "it is ok". 当我输入“ efgh”时,我想看到“没问题”。

First declare your arrays a as 首先声明您阵列a作为

char a[5];

use fgets to input string (do not use scanf ), then use strcmp or strncmp function to compare the two string/(literals). 使用fgets输入字符串(不要使用scanf ),然后使用strcmpstrncmp函数比较两个字符串/(文字)。

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. 如果您使用的是C ++和std::string类,则可以使用std::vector<string><algorithm>std::find查找字符串。

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. 由于您使用的是C样式的字符串,请在参考书中搜索strcmp以比较容器中的某项与C样式的字符串变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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