C# 如何突出显示文本文件中的背景文本?

C# 如何突出显示文本文件中的背景文本?,c#,winforms,linq,C#,Winforms,Linq,我有一个字典集合,它存储文本文件的起始位置和字符值 例如:示例文本文件(a.txt)可能包含“你好吗?你好吗?” 我已将上述文本编入索引如下 Dictionary<long,string> charLocation = new Dictionary<long,string>(); charLocation[0] = "how" charLocation[1] = "ow" charLocation[2] = "w" charLocation[4] = "are"

我有一个字典集合,它存储文本文件的起始位置和字符值

例如:示例文本文件(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?"
Dictionary charLocation=new Dictionary();
charLocation[0]=“如何”
charLocation[1]=“ow”
charLocation[2]=“w”
charLocation[4]=“是”
charLocation[6]=“e”
charLocation[5]=“re”
charLocation[11]=“?”
charLocation[9]=“ou?”
charLocation[10]=“u?”
charLocation[8]=“你?”
charLocation[13]=“如何”
charLocation[14]=“ow”
charLocation[15]=“w”
charLocation[17]=“do”
charLocation[18]=“o”
charLocation[21]=“ou”
charLocation[22]=“u”
charLocation[20]=“您”
charLocation[26]=“?”
charLocation[24]=“您要做什么?”
charLocation[25]=“o?”
现在,我想突出显示文本文件中出现的每个“how”或“do”

为此,我想首先在dictionary集合中进行查找,找到字符串的每个匹配项,然后打开文本文件并高亮显示每个匹配项的文本


我怎样才能做到这一点?

未经测试,但这应该可以工作

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;
}
如果我的代码没有错误,它将返回“
你怎么样?
你怎么样?”


然后,您可以使用任何您想“突出显示”文本的内容来重新添加

如何突出显示?在网页上?以某种形式?以某种深奥的XML格式,带有
关键字:)为什么不简单地搜索文本而不是使用索引?我需要突出显示文本文件本身中的搜索词。例如:搜索词的字体(“how”)可以更改如下,或者背景颜色可以更改为突出显示搜索词..请帮助
@Jens-我无法直接在文本中搜索单词,但我需要建立一个索引,然后在索引中搜索单词这与LINQ有什么关系?是什么阻止了你简单地搜索?性能问题?如果是这样的话,我认为你的索引在目前的形式下对你没有帮助。现在已经有了全文搜索算法,可能比任何一个可以快速破解的算法都要快。看看那里!对不起,我是c#programming的新手。。我无法理解我的问题解决方案的实施情况。你能帮我吗?我更新了我的答案。我建议您在调试模式下尝试它,在函数的第一行有一个断点,以了解它是如何工作的。
string myText = "how are you? how do you do?";
string hightLightedText = HighLight (0, myText, "how");