假设我有一个存储在char c
中的输入,并且在条件中我需要检查它是否是两个不同的字符,例如'n'
和'N'
。很明显,我可以使用逻辑OR
运算符进行条件化:
if(c == 'n' || c == 'N')
...
但是,如果只有两个以上的条件,那么就需要使用更多的逻辑运算符,编写,查看和编辑将变得冗长乏味。有没有办法压缩这个过程?使它看起来像这样的东西:
if(c == '[N][n]')
...
是否存在任何类型?
答案 0 :(得分:8)
您可以创建匹配字符的字符串,并查看字符串中是否存在相关字符:
char c;
std::string good_chars = "nNyYq";
if(good_chars.find(c) != std::string::npos) {
std::cout << "it's good!";
}
答案 1 :(得分:5)
低技术解决方案是使用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
这样的函数实际上应该成为性能瓶颈,这可能是相关的。
答案 2 :(得分:1)
如果您的扫描不区分大小写,则可以使用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