find the last index of a substring in a string in csharp

To find the last index of a substring within a given string, you can use the String.LastIndexOf method in C#. This method returns the index of the last occurrence of a specified substring within the given string, or -1 if the substring is not found.

Here's an example code that demonstrates how to use LastIndexOf method to find the last index of a substring in a string:

main.cs
string str = "I am a great programmer and I love coding";
string substr = "pro";

int lastIndex = str.LastIndexOf(substr);

if (lastIndex != -1)
{
    Console.WriteLine($"The last index of '{substr}' in '{str}' is {lastIndex}");
}
else
{
    Console.WriteLine($"'{substr}' is not found in '{str}'");
}
302 chars
14 lines

Output:

main.cs
The last index of 'pro' in 'I am a great programmer and I love coding' is 15
77 chars
2 lines

In the above example, we use LastIndexOf method to find the last index of the substring "pro" within the string "I am a great programmer and I love coding". Since "pro" appears at index 15, the LastIndexOf method returns 15. If the substring is not found, the method returns -1.

gistlibby LogSnag