Home » .Net

Explain LastIndexOf() method of String class with Example in C#

String.LastIndexOf() Method of String class in C#: Here, we will learn how to find the last index of any substring in C#.Net using LastIndexOf() method?

Given a string and we have to find the last index of a substring in C#.

String.LastIndexOf()

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)

Consider the program:

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 





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.
Learn PCB Designing: PCB DESIGNING TUTORIAL




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.