-
慕的地10843
尝试简单的字符串索引和子字符串操作,如下所示:string s = "2X+4+(2+2X+4X)+4";int beginIndex = s.IndexOf("(");int endIndex = s.IndexOf(")");string firstPart = s.Substring(0,beginIndex-1);string secondPart = s.Substring(endIndex+1,s.Length-endIndex-1);var result = firstPart + secondPart;解释:获取第一个索引 (获取第一个索引 )创建两个子字符串,第一个是 1 索引之前beginIndex删除数学符号,如 +第二个是 post endIndex,直到字符串长度连接两个字符串顶部得到最终结果
-
收到一只叮咚
尝试正则表达式方法:var str = "(1x+2)-2X+4+(2+2X+4X)+4+(3X+3)";var regex = new Regex(@"\(\S+?\)\W?");//matches '(1x+2)-', '(2+2X+4X)+', '(3X+3)'var result = regex.Replace(str, "");//replaces parts above by blank strings: '2X+4+4+'result = new Regex(@"\W$").Replace(result, "");//replaces last operation '2X+4+4+', if needed//2X+4+4
-
缥缈止盈
试试这个:var str = "(7X+2)+2X+4+(2+2X+(3X+3)+4X)+4+(3X+3)";var result = str .Aggregate( new { Result = "", depth = 0 }, (a, x) => new { Result = a.depth == 0 && x != '(' ? a.Result + x : a.Result, depth = a.depth + (x == '(' ? 1 : (x == ')' ? -1 : 0)) }) .Result .Trim('+') .Replace("++", "+");//result == "2X+4+4"这处理嵌套、前导和尾随括号。