2010-08-09 47 views
0

我有一個sql結果集,它是在使用LIKE關鍵字搜索數據庫後檢索的。我想在頁面上顯示結果,但不顯示整個文本。只是找到結果的段落。甚至可能會把這個特別的單詞加粗。任何人都知道我如何最好地實現這一點?在Haystack中查找字符串並顯示找到該字符串的特定段落

+0

可能是有用的http://www.codeproject.com/KB/string/fastestcscaseinsstringrep.aspx – PRR 2010-08-09 08:47:30

回答

2
  • 將文本轉換爲字符串。
  • 分割你的段落字符(換行符) - text.split('\n')
  • 遍歷每個段落
  • 讓您的關鍵字的索引(ES) - text.IndexOf("keyword")
  • 然後執行一些邏輯切字符數在開始和結束
  • 與例如字符串替換
  • 插入粗體標記 - text = text.Replace("keyword", "<b>keyword</b>")

[編輯 - 添加代碼示例]

public List<string> HighLightedParagraphs(string word, string text) 
{ 
    int charBeforeAndAfter = 100; 
    List<string> matchParagraphs = new List<string>(); 
    Regex wordMatch = new Regex(@"\b" + word + @"\b", RegexOptions.IgnoreCase); 
    foreach (string paragraph in text.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries)) 
    { 
     int startIdx = -1; 
     int length = -1; 
     foreach (Match match in wordMatch.Matches(paragraph)) 
     { 
      int wordIdx = match.Index; 
      if (wordIdx >= startIdx && wordIdx <= startIdx + length) continue; 
      startIdx = wordIdx > charBeforeAndAfter ? wordIdx - charBeforeAndAfter : 0; 
      length = wordIdx + match.Length + charBeforeAndAfter < paragraph.Length 
           ? match.Length + charBeforeAndAfter 
           : paragraph.Length - startIdx; 
      string extract = wordMatch.Replace(paragraph.Substring(startIdx, length), "<b>" + match.Value + "</b>"); 
      matchParagraphs.Add("..." + extract + "..."); 
     } 
    } 
    return matchParagraphs; 
} 
+0

感謝的Mikael,任何機會,你可以與樣品代碼幫助嗎? – Churchill 2010-08-09 08:01:51

+0

你真的應該能夠自己做到這一點,但我添加了一個簡短的示例。使用Regex而不是string.replace。 – 2010-08-09 09:01:56

+0

我正在使用您提供的方法並將其添加到我的數據集中。當我從我的中繼器使用<%#Eval(「Trimmed」)%>時,我得到System.Collections.Generic.List'1 [System.String] 我在做什麼錯? – Churchill 2010-08-09 09:45:33