0

我正在从文本文件中获取输入。我已阅读所有文本并将其标记化。

这是输入样本

.MAIN [
    .HEADING1 [ .TEXT 30000 ]
    .HEADING2 [
      [
        .TEXT1 YAMA
        .TEXT2 THAH
      ]
    ]
  ]

标记化后,标记列表包含“.MA​​IN”、“[”、“.HEADING1”等。现在我想为特定的起始方括号找到右括号的索引。例如,如果我给我的函数索引 0(第一个起始方括号)函数应该返回我最后一个索引,如果给我的函数索引 .HEADING1 的起始方括号,那么它应该返回我在同一行的右括号索引。

4

4 回答 4

2
int index = 3;
int bracketCount = 1;

for(int i = index + 1; i < tokenlist.Count; i++)
{
    if(tokenList[i] == "]")
    {
        bracketCount--;
    }
    if(tokenList[i] == "[")
    {
        bracketCount++;
    }
    if(bracketCount == 0)
    {
        index = i;
        break;
    }
}
于 2012-09-03T10:22:43.113 回答
1

试试这个:

        //Give it index of first bracket you want
        int myStartingIndex = 0;
        string s = "[ sfafa sf [fasfasfas ] [ test ] ]";
        int firstClosedIndex = s.IndexOf("]", myStartingIndex + 1);
        int firstOpenedIndex = s.IndexOf("[", myStartingIndex + 1);
        while (firstOpenedIndex < firstClosedIndex)
        {
            firstClosedIndex = s.IndexOf("]", firstClosedIndex + 1);
            firstOpenedIndex = s.IndexOf("[", firstOpenedIndex + 1);

            //Break if there is no any opened bracket
            //index before closing index
            if (firstOpenedIndex == -1)
            {
                break;
            }
        }

        Console.WriteLine("Required index is {0}", firstClosedIndex);
于 2012-09-03T10:22:24.547 回答
0

只需使用堆栈推开括号“[”并在“]”处弹出右括号。

于 2012-09-03T11:29:22.163 回答
0
public int FindClosingBracketIndex(string text, char openedBracket = '{', char closedBracket = '}')
        {
            int index = text.IndexOf(openedBracket);
            int bracketCount = 1;
            var textArray = text.ToCharArray();

            for (int i = index + 1; i < textArray.Length; i++)
            {
                if (textArray[i] == openedBracket)
                {
                    bracketCount++;
                }
                else if (textArray[i] == closedBracket)
                {
                    bracketCount--;
                }

                if (bracketCount == 0)
                {
                    index = i;
                    break;
                }
            }

            return index;
        }
于 2019-07-10T12:54:31.980 回答