VB.NET LastIndexOf Function

Use LastIndexOf and LastIndexOfAny Functions to search from the ending position of a string.

LastIndexOf. This Function searches a String in reverse. It checks a string from the last part of the string first, going backwards. With it we locate a pattern.

Another Function. LastIndexOfAny, meanwhile, searches for a string from an array argument. We can combine multiple LastIndexOf calls into 1 LastIndexOfAny call.IndexOf

LastIndexOf example. The first example (index1) shows how to find the last instance of a Char—the last "e" is located. A String argument can also be passed to LastIndexOf.Char
Note: If the String passed to LastIndexOf is not found, you will receive the value -1. This should be tested with an If-expression.
If Then
Case-insensitive: Use the argument StringComparison.OrdinalIgnoreCase. Lowercase and uppercase letters will be considered equal.
Result: The substring "PERLS" is found in the input string in the substring "Perls".
VB.NET program that uses LastIndexOf Module Module1 Sub Main() Dim value As String = "Dot Net Perls" ' Find a character. Dim index1 As Integer = value.LastIndexOf("e"c) Console.WriteLine("{0}, {1}", index1, value.Substring(index1)) ' Find a string. Dim index2 As Integer = value.LastIndexOf("Perls") Console.WriteLine("{0}, {1}", index2, value.Substring(index2)) ' Nonexistent. Dim index3 As Integer = value.LastIndexOf("Nope") Console.WriteLine(index3) ' Search case-insensitively. Dim index4 As Integer = value.LastIndexOf("PERLS", StringComparison.OrdinalIgnoreCase) Console.WriteLine("{0}, {1}", index4, value.Substring(index4)) End Sub End Module Output 9, erls 8, Perls -1 8, Perls

LastIndexOfAny. This finds the last position of an acceptable character. We pass it an array of Char(). It searches for any of the contained elements.
Here: We provide an array argument to LastIndexOfAny. The array must contain the set of characters you are trying to find.
Then: The function scans from the final character backwards. It checks for those characters one-by-one.
VB.NET program that uses LastIndexOfAny function Module Module1 Sub Main() ' Input string. Dim value As String = "aaBBccBB" ' Search for any of these Chars. Dim index As Integer = value.LastIndexOfAny(New Char() {"c", "a"}) Console.WriteLine(index) End Sub End Module Output 5

Performance. The LastIndexOfAny function is not ideal in its performance. You must allocate an array. With a custom For loop, you could avoid this allocation.For Each, For
Also: If you use LastIndexOfAny in a tight loop, you can allocate the Char() array outside the loop for better speed.
Char Array
Note: If you only need to locate one string, it is a better idea to use the LastIndexOf Function.

A summary. The IndexOf family of functions is often useful. With LastIndexOf, you can reverse the search order, giving precedence to the final instances of characters.

© 2007-2020 Sam Allen. Send bug reports to info@dotnetperls.com.