Quicker if-statement: if `variable` is “value” or “value”

前端 未结 7 2107
感情败类
感情败类 2020-12-18 15:44

How can you compare against multiple possibilities in one argument?

Example:

if ((integer == 2) || (integer == 5))

if ((string == \"hello\") || (str         


        
相关标签:
7条回答
  • 2020-12-18 16:32

    If your integers are nonzero and small enough to fit in unsigned char or wchar_t, a convenient way to do this is something like:

    if (strchr("\2\5", integer)) ...
    

    or:

    if (wcschr(L"\2\5", integer)) ...
    

    Keep in mind those are octal values, not decimal. You could use hex (\x) if you prefer.

    For strings, the way to make it efficient is to use a regular expression, or write your own DFA to accept the set of strings you want to test for.

    0 讨论(0)
提交回复
热议问题