2015-10-10 53 views
1

C#有一個辦法,我分析是這樣的:解析綴表達式,同時保持分隔符的數組元素

"(h1+h2+h3)" into a string array {"(", "h1", "+", "h2", +, "h3", + ")"} ? 

我實現調度場算法,我不想做一個爲沒有令牌而努力。

Shunting-yard algorithm

編輯:我只是寫我自己的解決方案

private string[] parseExp(string exp) 
{ 
     // it will be at least as long as the input string 
     string[] parsed = new string[exp.Length]; 
     int index = 0; 

     foreach(char c in exp) 
     { 
      if(op.Contains(c)) 
      { 
       index++; 
       parsed[index++] += c.ToString(); 
      }else 
      { 
       parsed[index] += c.ToString(); 
      } 
     } 

     Array.Resize(ref parsed, index + 1); 

     return parsed; 
} 

回答

0

您可以嘗試重新安排你的表情,讓您可以使用String.Split操作分開,但在這種情況下,你需要知道你的表情可能有的所有可能的符號。

string input="(h1+h2+h3)"; 
String newString = input.Replace("("," (").Replace(")",") 
" 
).Replace("+"," + "); // Reformat string by separating symbols 
String[] splitStr = newString.Split(new char[]{' '}); 
foreach(string x in splitStr) 
{ 
    Console.WriteLine(x);  
} 
相關問題