2012-09-03 55 views
0

我從文本文件獲取輸入。我已閱讀所有文本並將其標記。在字符串列表中查找右括號的索引

下面是輸入樣本

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

標記化後,令牌列表包含 「主要」, 「[」,」 .HEADING1" ,依此類推。現在我想查找特定起始方括號的右括號索引。例如,如果我給我的函數索引0(第一個起始方括號)函數應該返回我最後一個索引,並且如果給我的.HEADING1的方括號的函數索引,那麼它應該返回我在同一行的括號索引。

+1

將列表轉換爲樹結構。每個開放的括號是一個新的節點。 – BlueM

+0

顯示你的嘗試。 –

+0

如果沒有你的標記化(的結果)的概念,那麼不需要真正的答覆。 –

回答

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); 
+0

我認爲OP正在尋找標記的扁平字符串列表的索引,而不是單個字符串中的索引。 –

+0

哦,對不起,我不明白標記點 –

+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; 
    } 
} 
0

只使用一個堆棧推開括號 「[」,並在彈出 「]」 接近支架。

相關問題