Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <algorithm>
- #include <cctype>
- #include <string>
- namespace parser
- {
- class parse_symbol
- {
- constexpr bool is_letter(const char & C) const { return (C >= 'a') && (C <= 'z'); }
- constexpr bool is_number(const char & C) const { return (C >= '0') && (C <= '9'); }
- constexpr bool is_operator(const char & C) const { return (C == '-') || (C == '+') || (C == '*'); }
- public:
- parse_symbol() = default;
- constexpr int operator<<(const char & C) const
- {
- if (is_letter(C))
- return 1;
- else if (is_operator(C))
- return 2;
- else if (C == '(')
- return 3;
- else if (C == ')')
- return 4;
- return 0;
- }
- }; // End of 'parse_symbol' class
- static parse_symbol Parser;
- bool parse_string(std::string & Str)
- {
- if (Str.size() <= 0)
- return false;
- // remove spaces
- Str.erase(std::remove(Str.begin(), Str.end(), ' '), Str.end());
- // switch to lowercase
- std::transform(Str.begin(), Str.end(), Str.begin(), [](unsigned char c) { return std::tolower(c); });
- int state = 0; // 1 - letter, 2 - operation, 3 - end, 4 - ), 5 - btw
- for (auto & a : Str)
- {
- switch (Parser << a)
- {
- case 3: // (
- return ((Parser << Str.back()) == 4) ? parse_string(Str.substr(1, Str.size() - 2)) : false;
- break;
- case 1: // a
- switch (state)
- {
- case 0: // no
- case 2: // after op
- state++;
- break;
- default: // end or after a
- return false;
- break;
- }
- break;
- case 2: // +
- switch (state)
- {
- case 1: // after a
- state = 2;
- break;
- default:
- return false;
- break;
- }
- break;
- case 4: // )
- case 0: // odd symbols
- return false;
- break;
- }
- }
- return true;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement