C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
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 ThenCase-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 = "The Dev Codes"
' 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
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
Also: If you use LastIndexOfAny in a tight loop, you can allocate the Char() array outside the loop for better speed.
Char ArrayNote: If you only need to locate one string, it is a better idea to use the LastIndexOf Function.