与C++中不止一个字符进行比较

Comparing with more than one char in C++

本文关键字:字符 一个 比较 C++ 不止      更新时间:2023-10-16

>假设我有一个存储在char c中的输入,并且在条件中我需要检查它是否是两个不同字符中的任何一个,例如'n''N'。很明显,我可以用逻辑OR运算符制作条件:

if(c == 'n' || c == 'N')
...

但是,如果条件远远超过两个,那么这将需要使用更多的逻辑运算符,并且编写、查看和编辑将变得乏味。有没有办法压缩这个过程?为了使它看起来像这样的东西:

if(c == '[N][n]')
...

有没有这种东西存在?

您可以制作一个匹配字符的字符串,并查看字符串中是否存在相关字符:

char c;
std::string good_chars = "nNyYq";
if(good_chars.find(c) != std::string::npos) {
    std::cout << "it's good!";
}

一个低技术的解决方案是改用switch语句。如果您有很多匹配的字符,则使用case标签的阅读和编辑可能会容易得多。

bool matches(char c)
{
    switch (c)
    {
        case 'n':
        case 'N':
        case 'a':
        case 'b':
        case 'c':
        return true;
    }
    return false;
}

更高级的解决方案是将字符存储在容器中。 std::set将是一个选项:

bool matches(char c)
{
    // note: might want to use static storage for `chars`
    std::set<char> const chars =
    {
        'n',
        'N',
        'a',
        'b',
        'c',
    };
    return chars.find(c) != end(chars);
}

std::string允许更精简的形式,就可读性和可维护性而言,这可能是好是坏:

bool matches(char c)
{
    // note: might want to use static storage for `chars`
    std::string const chars = "nNabc";
    return chars.find(c) != std::string::npos;
}
请注意,不同的

容器具有不同的算法复杂性特征,如果像 match 这样的函数实际上应该成为性能瓶颈,这可能是相关的。

如果您的扫描不区分大小写,则可以使用以下方式使用 to_upper or to_lower API:

char c = 'n';
if( static_cast<unsigned char>('N') == std::toupper(static_cast<unsigned char>(c)) )
    // do something

或:

char c = 'n';
if( static_cast<unsigned char>('n') == std::tolower(static_cast<unsigned char>(c)) )
    // Do something
相关文章: