与C ++中的多个char比较 [英] Comparing with more than one char in C++

查看:107
本文介绍了与C ++中的多个char比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个存储在 char c 中的输入,在有条件的情况下,我需要检查它是否是两个不同字符之一,例如'n''N'。显然,我可以使用逻辑 OR 运算符作为条件:

Say I have an input that is stored in a char c, and in a conditional I need to check whether it is either of two different characters, for example 'n' and 'N'. It's obvious that I can make a conditional with a logical OR operator:

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

但是,如果存在两个以上的条件,则需要使用更多的逻辑运算符,并且编写,查看和编辑将变得很繁琐。有没有办法凝聚这个过程?要使其看起来像这样:

However, if there are significantly more than just two conditions, than that will require significantly more logical operators to be used, and it will become tedious to write, look at, and edit. Is there a way to condense this process? To make it look like something along the lines of this:

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

是否存在任何此类东西?

Does anything of the sort exist?

推荐答案

您可以创建一个由匹配字符组成的字符串,然后查看字符串中是否存在所涉及的字符:

You can make a string of your matching characters and see if the character in question exists in the string:

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

这篇关于与C ++中的多个char比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆