C#检查表达式是否有效

C# checking if expression is brackets valid(C#检查表达式是否有效)
本文介绍了C#检查表达式是否有效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

表达式:

"(a[i]+{-1}*(8-9))"

"( a[i]+{-1}*(8-9) )"

应该返回 true,因为这样编写语法是有效的.每个左括号都有一个正确的位置,并且所有括号都在合法位置.
我试图通过一个堆栈来做到这一点,我知道我错在哪里,但我想知道一种相关的方法来解决这个问题.谢谢!
我可怜可怜的错误代码:

should return true since it is valid to write syntax like this. Every left bracket has a right closer in the correct place and all brackets are at legal positions.
I tried to do this via one stack and I know where I'm wrong but I want to know a relevant way to solve this. thx!
My poor poor wrong code:

            string expression = "( a[i]+{-1}*(8-9) ) ";
        Stack<char> expStack = new Stack<char>();
        List<char> rightBracketsHolder = new List<char>();
        for (int i = 0; i < expression.Length; i++)
        {
            if (expression[i] == '{')
            {
                expStack.Push('}');
                Console.Write("}" + " ");
            }
            else if (expression[i] == '(')
            {
                expStack.Push(')');
                Console.Write(")" + " ");
            }
            else if (expression[i] == '[')
            {
                expStack.Push(']');
                Console.Write("]" + " ");
            }
        }
        Console.WriteLine();
        for (int i = 0; i < expression.Length; i++)
        {
            if (expression[i] == '}')
            {
                rightBracketsHolder.Add('}');
                Console.Write(expression[i] + " ");
            }
            else if (expression[i] == ')')
            {
                rightBracketsHolder.Add(')');
                Console.Write(expression[i] + " ");
            }
            else if (expression[i] == ']')
            {
                rightBracketsHolder.Add(']');
                Console.Write(expression[i] + " ");
            }
        }
        Console.WriteLine();
        bool stackResult = checkValidity(expStack, rightBracketsHolder);
        if (stackResult)
            Console.WriteLine("Expression is Valid.");
        else
            Console.WriteLine("
Expression is not valid.");
        Console.ReadKey();
    }

    private static bool checkValidity(Stack<char> expStack, List<char> leftBracketsHolder)
    {
        Console.WriteLine();
        int length = leftBracketsHolder.Count;
        for (int i = 0; i < length; i++)
        {
            if (expStack.Peek().ToString().Contains(leftBracketsHolder.ToString()))
            {
                leftBracketsHolder.Remove(expStack.Peek());
                expStack.Pop();

            }
        }
        if (expStack.Count == 0 && leftBracketsHolder.Count ==0)
        {
            return true;
        }
        return false;
    }
}

推荐答案

这段代码将解决你的目的-

This code will solve your purpose -

static void Main(string[] args)
    {
        bool error = false;
        var str = "( a[i]+{-1}*(8-9) )";
        Stack<char> stack = new Stack<char>();
        foreach (var item in str.ToCharArray())
        {
            if (item == '(' || item == '{' || item == '[')
            {
                stack.Push(item);
            }
            else if(item == ')' || item == '}' || item == ']')
            {
                if (stack.Peek() != GetComplementBracket(item))
                {
                    error = true;
                    break;
                }
            }
        }

        if (error)
            Console.WriteLine("Incorrect brackets");
        else
            Console.WriteLine("Brackets are fine");
        Console.ReadLine();
    }

    private static char GetComplementBracket(char item)
    {
        switch (item)
        {
            case ')':
                return '(';
            case '}':
                return '{';
            case ']':
                return '[';
            default:
                return ' ';
        }
    }

这篇关于C#检查表达式是否有效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)