如何编写字符串并查看它是否为表达式?

时间:2016-10-23 11:31:03

标签: c++ algorithm c++11 recursion c++14

我现在正在解决使用递归的算法问题。所以你需要在这个问题中找到的是,如果你输入的字符串是一个表达式。例如,你有字符串" 256 + 300-500" - 这是一个表达。所以表达式是一个包含数字和符号的字符串" +"和" - "。符号+和 - 不能保持一个靠近彼此,也不能在+或2 - 彼此附近。所以" 256 ++ 300"和" 256 + -600-500"不是表达。此外,如果数字中包含一个字母,那么它不是表达式" 54e2"。所以请帮我制作这个节目。我已经完成了查看数字字符串是否为数字的部分。

#include <iostream>
#include <cmath>
#include<string>
using namespace std;
int cif(char c)
{
if(isdigit(c))return 1;
else return 0;
}
int num (string s)
{
int z=s.length();
if(z==1) return cif(s[0]);
else
    {
      char c =s[0];
      s=s.substr(1);
      if(cif(c) && num(s))return 1; else return 0;
    }
}
int main()
{
 cout << num("2353Y3554");
 return 0;
}

这个程序的输出是0,因为它不是一个数字,如果是输出就是1.请帮我制作我需要继续使用这个程序的程序。

2 个答案:

答案 0 :(得分:4)

我认为您的问题为现代regex(和string)解决方案而哭泣

#include <iostream>
#include <string>
#include <regex>

int main(){

    std::regex expression{ "[\\d]+([-|+][\\d]+)+" };
    //Explanation:
    // [\\d]+  > at least one digit
    // ([-|+]  > - OR + character
    // [\\d]+  > at least one digit
    // )+      > at least once "- Or +" and "at least one digit" (grouping!)
    bool done = false;

    do {
        std::cout << "Type in an expression (\"+\" and/or \"-\" operator!): ";
        std::string str;
        std::cin >> str;

        if (std::regex_match(str, expression)){ //does match the rules!
            std::cout << "It's a valid expression!" << std::endl;
            done = true; //exit
        }
        else{ //it doesn't . . . type in again.
            std::cout << "That's not a valid expression . . . \n" << std::endl;
        }
    } while (!done);

    return 0;
}

代码运行示例:

Type in an expression ("+" and/or "-" operator!): Hello
That's not a valid expression . . .

Type in an expression ("+" and/or "-" operator!): 100+A
That's not a valid expression . . .

Type in an expression ("+" and/or "-" operator!): 100+
That's not a valid expression . . .

Type in an expression ("+" and/or "-" operator!): 100++42
That's not a valid expression . . .

Type in an expression ("+" and/or "-" operator!): +100+42
That's not a valid expression . . .

Type in an expression ("+" and/or "-" operator!): 100+42-50
It's a valid expression!

答案 1 :(得分:0)

使用小支票循环

bool is_leeter(char str)
{
    char abc[27]= "abcdefghijklmnopqrstuvwxyz";
    char ABC[27]= "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    for(int i=0;i<27;i++)
        if((abc[i] || ABC[i]) == str)
            return true;
    true false;
}

bool is_expression(char str)
{
    char exp[5]= "+-*/";
    for(int i=0;i<5;i++)
        if(exp[i] == str)
            return true;
    true false;
}

for(int i=0;i<strlen(str);i++)
{

    if(!is_leeter(str[i]) && !is_expression(str[i]) && !is_expression(str[i+1]))
    //do your thing