LastIndexOf
This C# method searches strings from the right. It finds the location of the last occurrence of a letter or substring. It is the reversed version of IndexOf
.
This string
method requires no explicit for
-loop. We also have the LastIndexOfAny
method, which searches for an array of strings.
LastIndexOf()
acts on instances of the string
type. These can be referenced by the string
keyword. There are many versions (overloads) of LastIndexOf
.
char
argument. LastIndexOf
searches the instance string
from the final character backwards to the first character.string
argument. If the value is located, its index is returned. Otherwise the special value -1 is returned.LastIndexOf
to do a case-insensitive search. This option is only available with the string
overloads of LastIndexOf
.using System; // The string we are searching. string value = "abc abc"; // Part 1: find the last occurrence of "a." int index1 = value.LastIndexOf('a'); if (index1 != -1) { Console.WriteLine(index1); Console.WriteLine(value.Substring(index1)); } // Part 2: find the last occurrence of this string. int index2 = value.LastIndexOf("ab"); if (index2 != -1) { Console.WriteLine(index2); Console.WriteLine(value.Substring(index2)); } // Part 3: find the last occurrence of this string, ignoring the case. int index3 = value.LastIndexOf("BC", StringComparison.OrdinalIgnoreCase); if (index3 != -1) { Console.WriteLine(index3); Console.WriteLine(value.Substring(index3)); }4 abc 4 abc 5 bc
LastIndexOfAny
This is a separate method. It searches for multiple characters in reverse. It returns the final position of any of a set of characters.
LastIndexOfAny
, we must provide a character array. This can be created directly in the argument slot.string
.using System; // Input string. const string value = "c_b_d_e"; // Search for last of any of these characters. int index = value.LastIndexOfAny(new char[] { 'd', 'b' }); Console.WriteLine(index);4
StringComparison
OrdinalIgnoreCase
specifies we want to treat chars as number values, not culture-specific values. When optimizing for performance, always try an "ordinal" argument.
LastIndexOf
and LastIndexOfAny
locate strings from the right side. LastIndexOf
can be used with a string
argument. But it can be called with a char
—this influences performance.