我有一个字典集合,用于存储文本文件的起始位置和字符值。
例如:示例文本文件(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?"
现在,我想强调文本文件中每次出现“how”或“do”。
为此,我想首先在字典集合中查找并查找字符串的每次出现,然后打开文本文件并突出显示每次出现的文本。
我该怎么做?
答案 0 :(得分: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>
。