我已经构建了一个小的 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")
. 这会崩溃,因为在德国, “ß”和“ss”被该方法认为是相等的,但它们的长度不同!IndexOf
现在,如果有办法找出“文本”中的匹配有多长,那就没问题了。记住这个长度可以!= substring.Length
。
那么如何找出IndexOf
在存在连字和外来语言字符(在这种情况下为连字)的情况下产生的匹配长度?