我有这段代码来检查 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
literal和 std::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/