【发布时间】:2010-05-14 15:32:35
【问题描述】:
我已经构建了一个小型 asp.net 表单,用于搜索某些内容并显示结果。我想在搜索结果中突出显示搜索字符串。示例:
Query: "p"
Results: a<b>p</b>ple, banana, <b>p</b>lum
我的代码是这样的:
public static string HighlightSubstring(string text, string substring)
{
var index = text.IndexOf(substring, StringComparison.CurrentCultureIgnoreCase);
if(index == -1) return HttpUtility.HtmlEncode(text);
string p0, p1, p2;
text.SplitAt(index, index + substring.Length, out p0, out p1, out p2);
return HttpUtility.HtmlEncode(p0) + "<b>" + HttpUtility.HtmlEncode(p1) + "</b>" + HttpUtility.HtmlEncode(p2);
}
我大部分时间都在工作,但可以试试HighlightSubstring("ß", "ss")。这会崩溃,因为在德国,IndexOf 方法认为 "ß" 和 "ss" 相等,但它们的长度不同!
现在,如果有办法找出“文本”中的匹配项有多长,那就没问题了。请记住,这个长度可以是!= substring.Length。
那么我如何找出IndexOf 在存在连字和外来语言字符(本例中为连字)的情况下产生的匹配长度?
【问题讨论】:
-
只是想知道:为什么只突出“apple”中的第一个“p”?
-
你说得对,我会修改它以突出显示所有匹配项 ;-) thx.
-
StringComparison.OrdinalIgnoreCase做你想做的事吗?
标签: .net encoding localization culture cultureinfo