我有一个字符串表达式,我需要根据以下条件对其进行评估:
("Hello" OR "World") AND (("Go" OR "Stay") NOT "Stop")
如何使用堆栈评估上述表达式?上述表达式正在文本文件中执行。
提前致谢:)
答案 0 :(得分:1)
我建议您使用Irony,它允许您定义自己的表达式并告诉解释器如何评估它。我在我的项目中使用了这个,与你的情况类似。我无法发布原始代码,因为它是用于商业用途,但它看起来像这样:
class CommandGrammar : Grammar //define your own grammar
{
public CommandGrammar(bool caseSensitive = false)
: base(caseSensitive)
{
var Command = new NonTerminal("Command");
Command.Rule = ToTerm("GO") | "STOP" | "STAY";
//these 3 tokens are called "command"
var And = new NonTerminal("And", ToTerm("AND"));
var Or = new NonTerminal("Or", ToTerm("OR"));
var Not = new NonTerminal("Not", ToTerm("NOT"));
//define 3 logical operators
var UnaryOperator = new NonTerminal("UnaryOperator");
var BinaryOperator = new NonTerminal("BinaryOperator");
var SimpleExp = new NonTerminal("SimpleExp");
var ParenthesizedExp = new NonTerminal("ParenthesizedExp");
var UnaryExp = new NonTerminal("UnaryExp");
var BinaryExp = new NonTerminal("BinaryExp");
var Exp = new NonTerminal("Exp");
//there are some possible expressions
//here are the rules for parsing the expression
UnaryOperator.Rule = Not;
BinaryOperator.Rule = And | Or;
SimpleExp.Rule = Command;
ParenthesizedExp.Rule = "(" + Exp + ")";
UnaryExp.Rule = (UnaryOperator + SimpleExp) | (UnaryOperator + ParenthesizedExp);
BinaryExp.Rule = Exp + BinaryOperator + Exp;
Exp.Rule = SimpleExp | ParenthesizedExp | UnaryExp | BinaryExp;
}
}
上面的代码只是一个例子,展示了库如何用你自己的语法解析你的表达式。您需要自己查看库,并实现语法。
答案 1 :(得分:0)
您无法将字符串与布尔表达式进行比较,例如& | ... 但是,我认为你试图说的是堆栈是否包含提到的字符串,你可以检查方法contains(obj)返回一个布尔值:
class Program
{
const string a = "Hello";
const string b = "World";
const string c = "Go";
const string d = "Stay";
const string e = "Stop";
static void Main(string[] args)
{
Stack st = new Stack();
st.Push(a);
st.Push(b);
st.Push(c);
st.Push(d);
st.Push(e);
if ((st.Contains("Hello") || st.Contains("World")) && ((st.Contains("Go") || st.Contains("Stay")) && (st.Contains("Stop") == false)))
{
Console.WriteLine("Success");
} // no success
//Remove "Stop" to match the expression
st.Pop();
if ((st.Contains("Hello") || st.Contains("World")) && ((st.Contains("Go") || st.Contains("Stay")) && (st.Contains("Stop") == false)))
{
Console.WriteLine("Success");
} //success
Console.ReadLine();
}
}