Home »
.Net »
C# Programs
C# - String.LastIndexOf() Method with Example
String.LastIndexOf() Method in C#: Given a string and we have to find the last index of a substring in C#
[Last updated : March 20, 2023]
String.LastIndexOf()
The string.LastIndexOf() method returns trimmed string that will contain leading and trailing spaces.
Syntax
int String.LastIndexOf(String str);
Example 1
Input string is:
"Hello there, how are you? Hello world."
Input substring (that we want to search) is:
"Hello"
Output will be:
26 (because the index of last "Hello" is 26)
Example 2
Input string is:
"Hello there, how are you? Hello world."
Input substring (that we want to search) is:
"Hi"
Output will be:
Substring not found (here function will return negative value)
C# program to demonstrate the example of String.LastIndexOf() method
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1 {
class Program {
static void Main() {
String str1;
String str2;
Console.Write("Enter string : ");
str1 = Console.ReadLine();
Console.Write("Enter sub string : ");
str2 = Console.ReadLine();
int index = str1.LastIndexOf(str2);
if (index < 0)
Console.WriteLine("Sub string is not find in string");
else
Console.WriteLine("Index str2 in str1 is: " + index);
}
}
}
Output
First run:
Enter string : Hello there, how are you? Hello world.
Enter sub string : Hello
Index str2 in str1 is: 26
Second run:
Enter string : Hello there, how are you? Hello world.
Enter sub string : Hi
Sub string is not find in string
C# Basic Programs »