c# '{' '}' 括号匹配

来源:互联网 发布:游戏界面编程 编辑:程序博客网 时间:2024/06/04 00:44

最近写代码  遇到了  {}进行匹配的问题  看了网上的一些  觉得有些部分不太适合我  就自己改了些 

不仅仅对“{”,“}” 的数量进行了匹配对比  ,还对 两个括号的写入顺序进行了判断。

/// <summary>        /// 判断符号是否匹配        /// </summary>        /// <param name="value"></param>        /// <returns></returns>        public bool syMatch(string content)        {            //符号是否正确            bool isCorrect = true;            //定义一个l,m变量 对"{", "}" 的写入顺序进行对比            int l = 0;            int m = 0;            if (content == null)            {                isCorrect = true;            }            else            {                Stack<char> stack = new Stack<char>();                for (int i = 0; i < content.Length; i++)                {                    if (content[i].Equals('{'))                    {                        stack.Push(content[i]);                        l++;                    }                    if (content[i].Equals('}'))                    {                        if (stack.Count != 0 && stack.Pop().Equals('{'))                        {                                                        continue;                        }                        else                        {                            m++;                            isCorrect = false;                        }                    }                }                if (stack.Count == 0 && l!=0  && m==0)                {                    isCorrect = true;                }                else if (stack.Count != 0)                {                    isCorrect = false;                }            }            return isCorrect;        }