在c#中检查左括号闭括号

时间:2016-03-01 08:03:03

标签: c# compiler-construction

我正在创建一个编译器。

当我为编译器编写输入代码时,如果缺少括号,编译器应显示错误。为此,我使用此代码:

Stack<int> openingbraces = new Stack<int>();
string output = string.Empty;

for (int i = 0; i < MELEdtior.Length; i++)
{
    if (MELEdtior[i] == '{')
    {
        openingbraces.Push(i);
        output="close braces missing";
    }
    else if (MELEdtior[i] == '}')
    {
        openingbraces.Push(i);
        output = "Open Braces missing";
    }   
}
if(openingbraces.Count==2)
{
    output = "Build Successfull";
}
else
{
    output = "brace missing";
}`

当我提供像function{}这样的简单输入时,它完美无缺。但我的意见是:

{global gHCIRCIN = OBSNOW("Head circumf")}
{IF gHCIRCCM <> "" AND HeadCircsDifferrev()  THEN
OBSNOW("Head circumf",str(rnd(ConvertCMtoIN(gHCIRCCM),2)))  ELSE "" ENDIF }

这里我的编译器应检查所有括号的正确性,并显示错误消息。

我实现这一点的想法是首先分开开括号和右括号,然后将它们配对,如果缺少任何一对,我的编译器应抛出一条错误信息。我该如何实现呢?

2 个答案:

答案 0 :(得分:0)

这是解决问题的迷你程序。基于o_weisman的评论。

class Program {
    static void Main(string[] args) {

        int currentOpenBracketNum = 0;
        string message = "Brackets OK";
        string input = @"{globa} }{IF gHCIRCCM <> """" AND HeadCircsDifferrev() THEN OBSNOW(""Head circumf"",str(rnd(ConvertCMtoIN(gHCIRCCM),2))) ELSE """" ENDIF }";

        foreach (char c in input) {
            if (c.Equals('{')) currentOpenBracketNum++;
            else if (c.Equals('}')) {
                if (currentOpenBracketNum > 0) {
                    currentOpenBracketNum--;
                } else {
                    message = "Missing open bracket";
                }
            }
        }

        if (currentOpenBracketNum > 0) {
            message = "Missing close bracket";
        }

        Console.WriteLine(message);
        Console.ReadKey(); // suspend screen
    }
}

注意:您可以跟踪您是否在&#34;字符并排除那些被视为字符串的计数,如果你想解决xanatos所指出的即将到来的问题。

答案 1 :(得分:0)

为避免引用区域中括号出现问题,我只想用RegEx替换它们。然后你可以计算出这些迹象:

char quoteChar = '"';
string s1 = "{global gHCIRCIN = OBSNOW(\"Head circumf\")} {IF gHCIRCCM <> \"\" AND HeadCircsDifferrev() THEN OBSNOW(\"Head circumf\",str(rnd(ConvertCMtoIN(gHCIRCCM),2))) ELSE \"\" ENDIF }";
string s2 = Regex.Replace(s1, quoteChar + ".*?" + quoteChar, "This_was_quoted");
int countOpening = s2.Count(c => c == '{');
int countClosing = s2.Count(c => c == '}');
MessageBox.Show(string.Format("There are {0} opening and {1} closing }}-signs.", countOpening, countClosing));