代码之家  ›  专栏  ›  技术社区  ›  Spartan

如何执行一个按位逻辑表达式,它是一个字符串,而运算符是以前不知道的

  •  0
  • Spartan  · 技术社区  · 7 年前

    例如:

    string s = "2 << 1"
    

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

    2 回复  |  直到 7 年前
        1
  •  1
  •   Zhavat    7 年前

    您可以尝试以下方法:

    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));
    
        2
  •  0
  •   Dmitrii Bychenko    7 年前

    你可以尝试使用 正则表达式 为了提取参数和操作,请执行以下操作:

      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);