Using C#'s `String.LastIndexOf()` Method: Finding the Last Occurrence of a Substring or Character

Learn how to use C#'s `String.LastIndexOf()` method to efficiently find the last occurrence of a specified character or substring within a string. This tutorial explains `LastIndexOf()`'s functionality, its overloads, and provides examples demonstrating its application in various string manipulation tasks.



Using C#'s `String.LastIndexOf()` Method

The C# `LastIndexOf()` method finds the last occurrence of a specified character or substring within a string. It's a very useful string manipulation function for tasks like finding the last position of a particular character or searching backward within a string.

`String.LastIndexOf()` Method Overloads

The `LastIndexOf()` method is overloaded, providing several versions for different search scenarios:

  • public int LastIndexOf(char value): Finds the last occurrence of a character.
  • public int LastIndexOf(char value, int startIndex): Finds the last occurrence of a character starting from a specified index.
  • public int LastIndexOf(char value, int startIndex, int count): Finds the last occurrence of a character within a specified range.
  • public int LastIndexOf(string value): Finds the last occurrence of a substring.
  • public int LastIndexOf(string value, int startIndex): Finds the last occurrence of a substring starting from a specified index.
  • public int LastIndexOf(string value, int startIndex, int count): Finds the last occurrence of a substring within a specified range.
  • public int LastIndexOf(string value, int startIndex, int count, StringComparison comparisonType): Allows for case-insensitive or culture-sensitive comparisons.
  • Other overloads for more advanced search options.

Parameters

The parameters typically include the character or substring to search for, the starting index for the search (searching backward from this index), the number of characters to search within, and an optional `StringComparison` value for specifying the type of comparison (case-sensitive or not).

Return Value

The method returns an integer representing the zero-based index of the last occurrence of the specified character or substring. If the character or substring is not found, it returns -1.

Example: Finding the Last Occurrence of a Character


string myString = "Hello world!";
int lastIndex = myString.LastIndexOf('l'); // lastIndex will be 9
Console.WriteLine(lastIndex);

`IndexOf()` vs. `LastIndexOf()`

The `IndexOf()` method finds the *first* occurrence of a character or substring, while `LastIndexOf()` finds the *last* occurrence. Both are essential for flexible string searching.


string str = "This is a test string.";
int firstIndex = str.IndexOf("is");  // firstIndex will be 2
int lastIndex = str.LastIndexOf("is"); // lastIndex will be 5