This article mainly describes the C # retrieval of case-insensitive and highlight the details of the relevant information, the need for friends can refer to the following
C # retrieves case insensitive and highlights instances
Today, there is a question: how to highlight a case-insensitive keyword in a Web page
For example: text abcabcabcabcabcabca, keyword BC, in case-insensitive cases, a total of 6 matches.
The ABCABCABCABCABCABCA is displayed in the Web page.
Many people think of the replace function. However, the Replace function in C # does not solve the case of letters.
For example, bc,bc,bc,bc are searched, but not uniformly replaced by a single text
The above text to arrogant cow "Vancan a millet" article-"highlight the case-insensitive keyword--asp."
But his article is written in the ASP version, today I write a C # version, the following talk about the solution.
Workaround: Use IndexOf
IndexOf (String, Int32, StringComparison)
The index of the first occurrence of the specified string in the current string object.
Parameters
Value type: System. String to search for. startindex type: System. Int32 Search start location. Comparisontype type: System. StringComparison One of the enumeration values that specifies the search rule. (OrdinalIgnoreCase: The string is compared by using an ordinal collation and ignoring the case of the string being compared.) )
Code
///<summary>///Highlight Find keywords. </summary>//<param name= "str" > Text. </param>//<param name= "keyword" > Keywords </param>//<returns> contains highlighted text. </returns>///<remarks>//1, letters are case-insensitive. 2, CssClass name is called 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 = highlightbegin.length + keyword. Length; var lengthhighlight = length + highlightend.length; while (index = str. INDEXOF (keyword, startIndex, stringcomparison.ordinalignorecase)) >-1) {str = str. Insert (index, Highlightbegin). Insert (index + length, highlightend); StartIndex = index + lengthhighlight; } return str; }