【问题标题】:How do I check if a single char is equal to at least one of given set of char?如何检查单个字符是否等于给定字符集中的至少一个?
【发布时间】:2013-04-13 02:53:13
【问题描述】:

抱歉标题。随意将其编辑为更清晰的内容。

我有一个字符串,我必须检查该字符串的第一个字符是否等于其他给定字符之间的至少一个,例如 B、Z 和 K(在我的情况下,我有大约 10 个字符要检查和它们不能归类为范围)。

我正在做如下检查。

if (string[0] == 'Z' || string[0] == 'K' || string[0] == 'B') {
   /* do something... */
}

有没有更简单的方法?

【问题讨论】:

标签: c string char


【解决方案1】:

一种可能的方法是在字符串中列出您的目标字符并使用strchr

const char* matches = "ZKB...";
if (strchr(matches, string[0]) != NULL) {
    /* do something */
}

【讨论】:

    【解决方案2】:
    #include <string.h>
    
    char* test = "ZKB";
    if (strchr(test, string[0]) != NULL)
    {
      // do stuff
    }
    

    【讨论】:

      【解决方案3】:

      将所有要比较的字符放在一个字符串中,然后将字符串的第一个字符存储在另一个字符串中,然后执行以下操作 strstr("firstChar","compareset"); 如果它返回 null 这意味着字符串的第一个字符不是来自集合

      【讨论】:

        【解决方案4】:

        如何创建一个数组来存储要检查的字符... 例如,如果它们在给定的第一个字符串中,则检查 A、B、C、D 这 4 个字符。 然后写一个函数:

        int check_first(char *s,char *t){ //string s is given,string t is chars which
                                          // will be checked.
            while(*t++ == *s){//You should leave 1 more byte in array to store '\0'
                return 1;
            }
            return 0;
        }
        

        【讨论】:

          猜你喜欢
          • 2014-01-14
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-05-29
          • 2011-10-13
          • 1970-01-01
          • 2012-07-21
          • 2016-07-20
          相关资源
          最近更新 更多