C# String LastIndexOf() Method

h‮//:sptt‬www.theitroad.com

The LastIndexOf() method in C# is used to find the index position of the last occurrence of a specified character or substring within a given string. It starts searching the string from the end and returns the index of the last occurrence of the specified character or substring. If the character or substring is not found, it returns -1.

The syntax of the LastIndexOf() method is as follows:

string.LastIndexOf(charOrSubstring);

or

string.LastIndexOf(charOrSubstring, startIndex);

Here, charOrSubstring is the character or substring to search for, and startIndex is the starting position of the search. The second syntax allows you to specify a starting position for the search.

For example, let's find the last occurrence of the letter "e" in the following string:

string text = "Hello, world!";
int lastIndex = text.LastIndexOf("e");
Console.WriteLine(lastIndex);  // Output: 10

In this example, the LastIndexOf() method is used to find the index position of the last occurrence of the letter "e" in the string "Hello, world!". The index position of the last "e" in the string is 10, so the output of the program is 10.

You can also use the LastIndexOf() method to search for a substring starting from a specified index position. For example:

string text = "Hello, world!";
int lastIndex = text.LastIndexOf("o", 7);
Console.WriteLine(lastIndex);  // Output: 4

In this example, the LastIndexOf() method is used to find the index position of the last occurrence of the letter "o" in the substring "world!" starting from the index position 7. The index position of the last "o" in the substring is 4, so the output of the program is 4.

You can also search for a single character using the LastIndexOf() method. For example:

string text = "Hello, world!";
int lastIndex = text.LastIndexOf('o');
Console.WriteLine(lastIndex);  // Output: 8

In this example, the LastIndexOf() method is used to find the index position of the last occurrence of the character 'o' in the string "Hello, world!". The index position of the last 'o' in the string is 8, so the output of the program is 8.