与C++中不止一个字符进行比较
Comparing with more than one char in C++
>假设我有一个存储在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
相关文章:
- 为什么 sscanf 无法从一个字符串中读取uint64_t和字符?
- 如何将一个ostringstream十六进制字符串字符对转换为单个unit8t等价的二进制值
- 如何检查一个c++字符串中有多少相同的字符/数字
- 使用.find函数在c++中查找字符和另一个字符之间的大小
- 我的目标是编写一个程序来计算和存储字符串在字符数组中出现的位置
- 关于字符数组,我正在尝试将数组中的每个字符分配给另一个值
- 我已经建立了递归关系,它找到了两个字符串之间最长的连续公共字符串,我怎么能跳过其中一个字符串中的一个字符
- 使用动态分配将 char* 复制到另一个字符**
- 将字符向量复制到另一个向量
- 如何将一个结构的字符数组复制到结构的另一个字符数组中?
- 如何在不知道对应关系的情况下在字符串中搜索字符并将其分配给另一个字符?
- 计算在同一位置至少包含一个常用字符的不同字符串对
- 如果我们在其中输入一个整数,则字符会给出整数作为输出,但是当分配给它一个整数时,这不会发生。为什么?
- 如何检查一个字符是否与字符数组中的另一个字符匹配?
- C++:使用另一个字符将一个字符大写
- 我可以得到一个字符 * 到一个 std::sregex_iterator 匹配 str() 吗?
- C ++读取用户输入的字符一个一个符号
- 遍历数组或从打开的文件中获取字符 - 一个比另一个有什么优势
- 将文本文件的内容一个字符一个字符地读入矢量,不跳过空白或新行
- 这是更快和更有效的,处理一个字符一个字符作为字符或流