C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Tip: LastIndexOf internally searches the instance string from the final character backwards to the first character.
Returns: If the specified value parameter is located, its index is returned. Otherwise the special value -1 is returned.
Start: When we specify the start index, specify the position where searching begins, not the first character in the range.
Insensitive: We use LastIndexOf to do a case-insensitive search. This option is only available with the string overloads of LastIndexOf.
C# program that uses LastIndexOf method
using System;
class Program
{
static void Main()
{
//
// The string we are searching.
string value = "The Dev Codes";
//
// Find the last occurrence of N.
int index1 = value.LastIndexOf('N');
if (index1 != -1)
{
Console.WriteLine(index1);
Console.WriteLine(value.Substring(index1));
}
//
// Find the last occurrence of this string.
int index2 = value.LastIndexOf("Perls");
if (index2 != -1)
{
Console.WriteLine(index2);
Console.WriteLine(value.Substring(index2));
}
//
// Find the last 'e'.
// ... This will not find the first 'e'.
int index3 = value.LastIndexOf('e');
if (index3 != -1)
{
Console.WriteLine(index3);
Console.WriteLine(value.Substring(index3));
}
//
// Find the last occurrence of this string, ignoring the case.
int index4 = value.LastIndexOf("PERL",
StringComparison.OrdinalIgnoreCase);
if (index4 != -1)
{
Console.WriteLine(index4);
Console.WriteLine(value.Substring(index4));
}
}
}
Output
4
Net Perls
8
Perls
9
erls
8
Perls
Tip: When we call LastIndexOfAny, we must provide a character array. This can be created directly in the argument slot.
Char ArrayHere: The example searches for the first instance of a "d" or "b" character starting from the end of the string.
And: The position returned is 5, which is the final "d" in the input string. The search terminates when something is found.
C# program that uses LastIndexOfAny method
using System;
class Program
{
static void Main()
{
// Input string.
const string value = "ccbbddee";
// Search for last of any of these characters.
int index = value.LastIndexOfAny(new char[] { 'd', 'b' });
Console.WriteLine(index);
}
}
Output
5
Tip: When optimizing for performance, always try an "ordinal" argument. But make sure to have a correct program first.
Note: This will avoid an object creation on every call. Reducing object creations reduces memory pressure and garbage collections.