我从文本文件中获取输入。我已阅读所有文字并将其标记化。
这是输入样本
.MAIN [
.HEADING1 [ .TEXT 30000 ]
.HEADING2 [
[
.TEXT1 YAMA
.TEXT2 THAH
]
]
]
标记化后,标记列表包含“.MAIN”,“[”,“。HEADING1”等。现在我想要找到特定起始方括号的右括号索引。例如,如果我给我的函数索引0(第一个起始方括号)函数应该返回我最后一个索引,如果给我的函数索引开始方括号.HEADING1那么它应该返回我在同一行的结束括号的索引。
答案 0 :(得分: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;
}
}
答案 1 :(得分: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);
答案 2 :(得分:0)
只需使用堆栈推开括号“[”并弹出“]”关闭括号。
答案 3 :(得分: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;
}