用于检查 char 数组是否仅包含允许的字符的函数
function for checking if a char array contains only allowed chars
如何更改/删除这个可怕的"如果"。该函数正在检查字符数组"方程"是否仅包含 0 到 9 的数字和"if"中的符号。
bool containsOnlyAllowedSymbols(const char* equation)
{
bool a;
while (*equation) {
if ((*equation < 48 || *equation > 57) && *equation != '+' && *equation != '-' && *equation != '*' && *equation != '/' && *equation != '(' && *equation != ')' && *equation != '[' && *equation != ']' && *equation != '{' && *equation != '}') {
return false;
}
else
a = true;
equation++;
}
return a;
}
我会很想像这样使用好的老式std::strspn:
bool containsOnlyAllowedSymbols(const char* equation)
{
return std::strspn(equation, "0123456789+-*/()[]{}") == std::strlen(equation);
}
我建议使用std::regex_match:
std::regex pattrn("[0-9*/+-]+");
bool only_legal_equation_chars(char const * equation)
{
return std::regex_match(equation, equation+strlen(equation), pattern);
}
std::all_of
在这里非常合适:
std::string mystr{"123+-*["};
auto is_allowed_character = [](unsigned char x) //related to C
{
return (x >= 48 && x <= 57) ||
x == '+' ||
//so on
;
}
return std::all_of(mystr.begin(), mystr.end(),
is_allowed_character);
我删除了if
,循环,并使其更惯用C++。此外,该事物可以在任何迭代器上运行,甚至是由std::cin
制成的迭代器。
另一个regex
解决方案:
#include <iostream>
#include <regex>
bool containsOnlyAllowedSymbols(char const *equation)
{
std::regex re(R"([^0-9(){}[]*+-/])");
return !std::regex_search(equation, re);
}
int main()
{
std::cout << containsOnlyAllowedSymbols("(10+20)-200*4") << std::endl;
std::cout << containsOnlyAllowedSymbols("10+20-{200}abc") << std::endl;
return 0;
}
https://ideone.com/wR0yA0
如果表达式可以包含空格,则向正则表达式模式添加空格。
相关文章:
- 为字符串中每 N 个字符插入空格的函数没有按照我认为的方式工作?
- 使用.find函数在c++中查找字符和另一个字符之间的大小
- 将字符随机转换为大写的函数
- 固有构造函数的字符和访问级别
- constexpr 函数获取常量字符*
- 将字符缓冲区强制转换为函数指针
- 函数签名与调用的函数不匹配,常量字符[]和字符*之间的区别?
- 将字符串数组传递给接受常量字符**的函数
- 在函数中返回无符号字符数组,但不返回指针
- 如何返回实际值(在我的例子中是无符号字符数组)而不是来自 C++ 函数的指针?
- 在函数 strcpy() 中访问字符数组时出现分段错误
- 如何循环访问 cpp 中的函数返回的字符指针数组
- 自定义 std::fstream,std::filebuf 的溢出和下溢函数未为每个字符调用
- 如何在字符函数中选择某些字符?
- 使用排序函数 c++ 对字符数组进行排序
- 字符串到字符* 函数
- 空间字符函数
- 在字符函数中传递字符值时出现奇怪的错误
- 正在更新字符* 函数C++
- 反转字符函数,但不会输出