Reputation: 7277
I am getting input from a text file. I have read all the text and tokenized it.
Here is input sample
.MAIN [
.HEADING1 [ .TEXT 30000 ]
.HEADING2 [
[
.TEXT1 YAMA
.TEXT2 THAH
]
]
]
After tokenization, tokens list contains ".MAIN", "[", ".HEADING1", and so on. Now what I want to find index of closing bracket for a particular starting square bracket. For example if i give my function index 0 (the first starting square bracket) function should return me last index, and if give my function index of starting square bracket of .HEADING1 then it should return me index of closing bracket at same line.
Upvotes: 0
Views: 3168
Reputation: 9624
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;
}
Upvotes: 0
Reputation: 698
just use a stack to push open bracket "[" and Pop at "]" close bracket.
Upvotes: 0
Reputation: 5039
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;
}
}
Upvotes: 2
Reputation: 8686
Try this one:
//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);
Upvotes: 1