2015-07-21 19 views
-1

我正在一個項目中,我有很多像((A和B和(C或(D和E)))或F)括號的字符串。我需要找到一種方法來查找對和樣式或爲它們着色以顯示它們匹配。例如,「D和E」周圍的括號爲綠色,「C或(D和E)」周圍的爲藍色。對於匹配對,我使用堆棧,但找不到設置顏色的方法,如果這是我打開試用的更好方法。我在asp.net和C#工作。謝謝!如何在字符串中查找和樣式匹配的括號對?

編輯:這裏是生成字符串的代碼。 terms是值的列表,innerConnector是基於用戶輸入的「and」或「or」,而子組是大組內的組。 (A和(B或C))A將是一個術語,(B或C)將是一個小組。我想採用返回的字符串並將顏色應用於圓括號。

public string toString() 
    { 
     string str = "("; 
     if(terms.Count > 0) 
     { 
      for(int i = 0; i < terms.Count; i++) 
      { 
       if(i == 1) 
       { 
         str += terms[i]; 
       } 
       else 
       { 
        str += " " + innerConnector + " " + terms[i]; 
       } 
      } 
     } 
     if(children != null) 
     { 
      for(int i = 0; i < terms.Count; i++) 
      { 
       if(i == 1 && terms.Count == 0) 
       { 
        str += childGroups[i].toString(); 
       } 
       else 
       { 
        str += " " + innerConnector + " " childGroups[i].toString();  
       } 
      } 
     } 
     str += ")"; 
    } 
+0

你不應該使用的顏色進行編碼的,這不是它如何在現實世界中完成的。如果你編碼很多,你會習慣支架對齊。雖然你可能在談論括號?你可以把它們分開,它不應該影響代碼。你可以把它們放在不同的線上,但我不會篡改IDE的顏色。 –

+0

爲什麼javascript包含在這裏?另外,假設括號不能做到這一點((A和[B和C)和D]'''''''''''''''''''''' – JBux

+0

我應該澄清,我沒有使用顏色來編碼。我使用它們來呈現信息,因此更容易遵循。我給出了用戶輸入的字符串,我想在網頁上顯示帶有彩色圓括號的字符串,或者以其他方式顯示對,以便用戶可以更輕鬆地看到分組。 –

回答

1

我看到您已將javascript從問題標記中移除。然後忽略下面。


這實際上很有趣。這不是最優雅的解決方案!

我稍微評論了一下代碼,因爲我是一個很可愛的小夥子。

// List of colours we'll use. 
var colors = ['red', 'blue', 'purple', 'orange', 'green']; 

// Define the div and it's contents 
var div = document.getElementById('colors') 
var string = div.innerHTML; 

// A function to return a span object with coloured text. 
color_span = function(color, inner) { 
    return '<span style="color:' + color + '">' + inner + '</span>' 
} 

var color_count = 0; 
var return_html = ''; 

// Cycle through each character in the string 
for (i=0; i < string.length; i++) { 
    // If it's an open bracket, add a coloured span to the return_html and increment the colour counter 
    if (string[i] == '(') { 
     return_html += color_span(colors[color_count], string[i]); 
     color_count++; 
    // If close bracket add coloured span and decrement the colour counter. 
    } else if (string[i] == ')') { 
     color_count--; 
     return_html += color_span(colors[color_count], string[i]); 
    // If neither just add the character. 
    } else { 
     return_html += string[i]; 
    } 
} 
// Change the div's html. 
div.innerHTML = return_html 

JSFiddle

相關問題