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.
LastIndexOfAny
, meanwhile, searches for a string
from an array argument. We can combine multiple LastIndexOf
calls into 1 LastIndexOfAny
call.
LastIndexOf
exampleThe 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
.
String
passed to LastIndexOf
is not found, you will receive the value -1. This should be tested with an If
-expression.Module Module1 Sub Main() Dim value As String = "Dot Net Perls" ' Find a character. Dim index1 As Integer = value.LastIndexOf("e"c) Console.WriteLine(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 Module9 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.
LastIndexOfAny
. The array must contain the set of characters you are trying to find.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 Module5
The LastIndexOfAny
function is not ideal in its performance. You must allocate an array. With a custom For loop, you could avoid this allocation.
LastIndexOfAny
in a tight loop, you can allocate the Char()
array outside the loop for better speed.string
, it is a better idea to use the LastIndexOf
Function.The IndexOf
family of functions is often useful. With LastIndexOf
, you can reverse the search order, giving precedence to the final instances of characters.