×

C# Tutorial

Basics of .Net

C# Basics

C# Fundamentals

C# Operators

C# Loops

C# Type Conversions

C# Exception Handling

C# String Class

C# Arrays

C# List

C# Stack

C# Queue

C# Collections

C# Character Class

C# Class and Object

C# Namespaces

C# Delegates

C# Constructors

C# Inheritance

C# Operator Overloading

C# Structures

C# File Handling

C# Convert.ToInt32()

C# Int32 (int) Struct

C# DateTime Class

C# Uri Class

C# Database Connectivity

C# Windows

C# Other Topics

C# Q & A

C# Programs

C# Find O/P

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 »

Advertisement
Advertisement

Comments and Discussions!

Load comments ↻


Advertisement
Advertisement
Advertisement

Copyright © 2025 www.includehelp.com. All rights reserved.