find and solve || findandsolve.com
Please wait.....

C# String LastIndexOf() Method

In the C# LastIndexOf() method is used to find index position of the last occurrence of a specified character within String or It finds the location of the last occurrence of a letter or substring.

Syntax

public int LastIndexOf(Char ch)  
public int LastIndexOf(Char, Int32)
public int LastIndexOf(Char, Int32, Int32)
public int LastIndexOf(String)
public int LastIndexOf(String, Int32)
public int LastIndexOf(String, Int32, Int32)
public int LastIndexOf(String, Int32, Int32, StringComparison)
public int LastIndexOf(String, Int32, StringComparison)
public int LastIndexOf(String, StringComparison)  

Parameter

ch: It is a character type parameter which is used to finds the location of the last occurrence of a letter or substring.

Return

It returns integer value.

Example

The LastIndexOf() method returns the index position of the last occurrence of a specified character or string within the given string.

using System;
public class Program
{
 public static void Main()
 {
      string str = "Hello FindAndSolve";
      // returns last index of 'D'
      int index = str.LastIndexOf('e');
      Console.WriteLine(index);
 }
}

Output 

17

C# String LastIndexOf() With startIndex and count

using System;
public class Program
{
 public static void Main()
 {
      string str = "FindAndSolve";
      int startIndex = 4;
      int count = 3;
      // returns -1 as 'S' is not found
      int index = str.LastIndexOf('S', startIndex, count);
      Console.WriteLine(index);
 }
}

Output

-1

C# String IndexOf() vs LastIndexOf() Example

The IndexOf() method returns the index number of the first matched character whereas the LastIndexOf() method returns index number of the last matched character.

using System;
public class Program
{  public static void Main()
 {
           string str = "Hello FindAndSolve";
           int first = str.IndexOf('l');
           int last = str.LastIndexOf('l');
           Console.WriteLine(first);
           Console.WriteLine(last);

 }
}

Output

2

15