如何写一个字符串,看看它是否是一个表达式

How to write a string and see if it is an expression?

本文关键字:一个 表达式 何写一 字符串 是否是      更新时间:2023-10-16

我正在用递归解决一个算法问题。在这个问题中你需要找出的是如果你输入的字符串是一个表达式。例如,你有一个字符串"256+300-500"——这是一个表达式。因此,表达式是包含数字和符号"+"answers"-"的字符串。符号"+"answers"-"不能离得太近,也不能离得太近。所以"256++300"answers"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。

请帮我制作我需要继续这个项目的程序。

我认为你的问题呼唤一个现代的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!

use loop with small check

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