c++ - 在 if 语句中处理多个或的更优雅的方法是什么

标签 c++ arrays for-loop if-statement

我有这段代码来检查 char 数组中的每个字符是否满足一组属性: * 是一个数字 * 或者是 (+, -, *,/)

bool chkArray(char input[]) {
    for (auto x = 0; x < strlen(input); x++) {
        if (isdigit(input[x]) || input[x] == '+' || input[x] == '-' || input[x] == '*' || input[x] == '/' || input[x] == ' ') {
            continue;
        }
        else {
            return false;
        }
    }
    return true;
}

我觉得有一种更优雅的方式来处理检查 (+, -, *,/) 的多个或。像这样:

bool chkArray(char input[]) {
    for (auto x = 0; x < strlen(input); x++) {
        if (isdigit(input[x]) || input[x] == '+', '-', '*', '/', ' ') {
            continue;
        }
        else {
            return false;
        }
    }
    return true;
}

所以我现在想知道是否有人可以替代原始代码以使其更优雅?

最佳答案

从 c++14 开始,最惯用的方法可能是使用 std::string literalstd::string::find()功能:

#include <iostream>
#include <iomanip>
#include <string>
#include <cctype>

using namespace std::literals::string_literals;

int main()
{
    std::string input = "Hello world5!"s;

    for(auto c : input) {
        std::cout << std::boolalpha 
                  << (std::isdigit(c) || "+-*/ "s.find(c) != std::string::npos) 
                  << '\n';
    }      
}

输出:

false
false
false
false
false
true
false
false
false
false
false
true
false

查看工作 example .

关于c++ - 在 if 语句中处理多个或的更优雅的方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51407392/

相关文章:

c++ - 在 Linux 上使用纯 C 项目中用 C++ 编写的库?

java - 从二维对象数组(java)调用时看不到方法?

java - 有没有一种简单的方法可以强制 String.split() 返回具有空字符串元素的数组?

C++如何增加For循环增量

java - 如何检查并显示其他两个特定单词之间的单词?

r - 以增长率预测时避免循环

c++ - 用户定义类的运算符重载在 C++ 中不起作用

c++ - C/C++ 中的套接字编程 - gcc char * 警告

c++ - C++CLI 的 *var* 关键字

javascript - MongoDB 如何通过索引替换数组项