2011-08-01 48 views
-2

我有一個字典集合,用於存儲文本文件的起始位置和結構元素值。如何突出顯示文本文件中的背景文字?

例如:示例文本文件(a.txt)可能包含文本,如「你好嗎?你好嗎?」

我已經收錄了上述案文如下

Dictionary<long,string> charLocation = new Dictionary<long,string>(); 

charLocation[0] = "how" 
charLocation[1] = "ow" 
charLocation[2] = "w" 
charLocation[4] = "are" 
charLocation[6] = "e" 
charLocation[5] = "re" 
charLocation[11] = "?" 
charLocation[9] = "ou?" 
charLocation[10] = "u?" 
charLocation[8] = "you?" 
charLocation[13] = "how" 
charLocation[14] = "ow" 
charLocation[15] = "w" 
charLocation[17] = "do" 
charLocation[18] = "o" 
charLocation[21] = "ou" 
charLocation[22] = "u" 
charLocation[20] = "you" 
charLocation[26] = "?" 
charLocation[24] = "do?" 
charLocation[25] = "o?" 

現在,我想強調的每次出現「如何」或在文本文件中「做」。

爲此,我想先在字典集合中查找並查找字符串的每個出現位置,然後打開文本文件並突出顯示每個出現的文本。

我該怎麼做?

+3

突出顯示如何?在網頁上?在一個表單中?在一些深奧的XML格式與''關鍵字? :) –

+0

你爲什麼不簡單地搜索文本,而不是使用你的索引? – Jens

+0

我需要突出顯示文本文件本身的搜索詞。例如:搜索詞的字體(「如何」)可以改變如下**如何**或背景顏色可以改變,突出搜索詞..請幫助!
@Jens - 我無法直接在文本中搜索單詞,但我需要建立一個索引,然後搜索索引詞 – Fraiser

回答

0

未經測試,但這應該有效。

public string HighLight (int startPoint, string text, string word) 
{ 
    if (startPoint > = 0) 
    { 
    int startIndex = text.indexOf (word, startPoint); 
    if (startIndex >= 0) 
    { 
     StringBuilder builder = new StringBuilder(); 
     builder.Append (text.Substring (0, startIndex)); 
     builder.Append ("<strong>"); 
     builder.Append (text.Substring (startIndex + 1, word.Length)); 
     builder.Append ("</strong>"); 
     builder.Append (text.Substring (startIndex + word.Length + 1)); 
     return HighLight ((startIndex + "<strong>".Length + "</strong>".Length + word.Length, builder.ToString(), word); 
    } 
    } 

    //Word not found. 
    return text; 
} 

所以,你可以這樣做:

string myText = "how are you? how do you do?"; 
string hightLightedText = HighLight (0, myText, "how"); 

如果我的代碼沒有錯誤,這將返回 「<strong>如何</strong><strong></strong>你怎麼辦?」;

然後你可以用你想「突出顯示」你的文字的方式來代替<strong></strong>

+0

對不起,我是c#編程的新手。我無法理解解決方案對我的問題的執行情況。你可以幫我嗎? – Fraiser

+0

我更新了我的答案。我建議你在調試模式下嘗試一下,在函數的第一行有一個斷點,以瞭解它是如何工作的。 – Johnny5

+0

謝謝你的解決方案.. – Fraiser