C# Retrieve case-insensitive and highlight instance details
Today, I encountered a problem: how to highlight case-insensitive keywords in web pages
For example: the text abcaBcabCaBCabcaBCa, the keyword bc, has a total of 6 matches in case insensitive situations.
Then the abcaBcabCaBCabcaBCa is displayed on the web page.
Many people think of it as a replace function. However, the replace function in c# cannot solve the problem of letter case.
For example, bc, Bc, bC, and BC have all been searched, but cannot be replaced with a text in a uniform manner
The above text is reproduced from the article "Wancang Yishu" by Daniu--"Highlighting the case-insensitive keyword - ASP".
But his article is written in the ASP version, and today I write in the C# version; let’s talk about the solution below.
Solution: Use IndexOf
IndexOf(String, Int32, StringComparison)
The index of the specified string's first match in the current String object.
parameter
value type: System. String String to search。 startIndex type: System. Int32 Search for the starting location。 comparisonType type: System. StringComparison Specify one of the enumeration values for the search rule。 (OrdinalIgnoreCase:Use sequence number collation and ignore case of string being compared,Comparison of strings。)
Code
/// <summary> /// Highlight to find keywords. /// </summary> /// <param name="str">text. </param> /// <param name="keyword">Keyword</param> /// <returns> Text with highlighted logo. </returns> /// <remarks> /// 1. Letters are case-insensitive. /// 2. The name of CssClass is highlight. /// </remarks> private string HighLightKeyword(string str, string keyword) { int index; var startIndex = 0; const string highLightBegin = "<span class='highlight'>"; const string highLightEnd = "</span>"; var length = + ; var lengthHighlight = length + ; while ((index = (keyword, startIndex, )) > -1) { str = (index, highLightBegin).Insert(index + length, highLightEnd); startIndex = index + lengthHighlight; } return str; }
Thank you for reading, I hope it can help you. Thank you for your support for this site!