In ASP.Net 2.0, C# provides LastIndexOf string function that is most often used to get the position of the string pattern passed to the LastIndexOf function. C# LastIndexOf string function as the name suggests returns the last occurrence of the specified string pattern in the provided string. LastIndexOf string function works as the reverse of IndexOf function that returns the first occurrence of the string pattern from the target string as we learnt in the previous tutorial on ASP.Net C# IndexOf String function. C# LastIndexOf string function starts searchin from the last index to the first index of the specified string to get the last occurrence of the string pattern. You can also find the second or third occurrence from the last, of the specified string pattern from the target string. Before starting with code examples take a look on some of the overloads of the C# LastIndexOf string function:
Above mentioned overloads of C# LastIndexOf function accepts four types of parameters. First parameter type accepts the char or string type value that is the string or character, whose index of last occurrence is to be retrieved. Second type of parameter is integer type start index of the string from which LastIndexOf string function starts searching towards the 0th index of the target string. Third type of parameter is integer type count or number of character within which LastIndexOf function performs searching.
Last parameter type is enumerator of StringComparison. It accepts the following options for comparisonType based on Culture and Case of string letters.
In ASP.Net, C# LastIndexOf string function returns the index of specified string pattern if it exists in the string. It returns -1 if specified string pattern does not exist and returns 0 if string is Empty.
Response.Write("<br /><br />"); Response.Write("Last Index of \"STR\" upper case string with startIndex=20, count=15 and CurrentCultureIgnoreCase: <b>" + strText.LastIndexOf("Str", 20, 15, StringComparison.CurrentCultureIgnoreCase) + "</b>");
Output
Last Index of '$' from complete string: 50 Last Index of "str" from complete string: 39 Last Index of "str" string with startIndex=5: -1 Last Index of "str" string with startIndex=20 and count=15: 17 Last Index of "STR" upper case string with startIndex=20, count=15 and CurrentCultureIgnoreCase: 17
Above examples show the use of C# LastIndexOf string function using different overloads of LastIndexOf function. In the last example with StringComparison comparisonType parameter value CurrentCultureIgnoreCase is used to search within the string without case-sensitive approach.
Be the first to rate this post
Tags: asp.net 2.0, c#, c# lastindexof function, c# indexof function, c# string function, asp.net string function, asp.net lastindexof string function, asp.net indexof string function, c# split, c# lastindexof, c# indexof, c# replace, c# remove, c# replace, c# code, asp.net examples
8/23/2008 8:44:30 PM