用于检查 char 数组是否仅包含允许的字符的函数

function for checking if a char array contains only allowed chars

本文关键字:字符 函数 包含允 检查 char 数组 是否 用于      更新时间:2023-10-16

如何更改/删除这个可怕的"如果"。该函数正在检查字符数组"方程"是否仅包含 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

如果表达式可以包含空格,则向正则表达式模式添加空格。