事先不知道如何执行按位表示的逻辑表达式,该表达式是字符串,并且运算符

时间:2019-02-12 07:24:39

标签: c# logical-operators

我必须执行一个逻辑表达式,它是一个字符串。

例如:

string s = "2 << 1"

在执行时如何使用未知的按位运算符执行“ s”以上的内容。

2 个答案:

答案 0 :(得分:1)

您可以尝试以下操作:

string s = "2 << 1";
string operator_ = (new string(s.Where(c => !char.IsDigit(c)).ToArray())).Trim();
int operand1 = Convert.ToInt32(s.Substring(0, s.IndexOf(operator_)).Trim());
int operand2 = Convert.ToInt32(s.Substring(s.IndexOf(operator_) + operator_.Length).Trim());

int result = 0;
switch (operator_)
{
    case "<<":
         result = operand1 << operand2;
         break;
    case ">>":
         result = operand1 >> operand2;
         break;
}
Console.WriteLine(string.Format("{0} {1} {2} = {3}", operand1, operator_, operand2, result));

答案 1 :(得分:0)

您可以在此处尝试使用正则表达式来提取参数和操作:

  using System.Text.RegularExpressions; 

  ...

  // Let's extract operations collection 
  // key: operation name, value: operation itself 
  Dictionary<string, Func<string, string, string>> operations =
    new Dictionary<string, Func<string, string, string>>() {
    { "<<", (x, y) => (long.Parse(x) << int.Parse(y)).ToString() },
    { ">>", (x, y) => (long.Parse(x) >> int.Parse(y)).ToString() }
  };

  string source = "2 << 1";

  var match = Regex.Match(source, @"(-?[0-9]+)\s*(\S+)\s(-?[0-9]+)");

  string result = match.Success
    ? operations.TryGetValue(match.Groups[2].Value, out var op) 
       ? op(match.Groups[1].Value, match.Groups[3].Value)
       : "Unknown Operation"  
    : "Syntax Error";

  // 4
  Console.Write(result);