Q:

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

belongs to collection: C# Basic Programs | String programs

0

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)

 

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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 

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C# Basic Programs | String programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Explain String.Split() method of String class in C... >>
<< Compare strings using Equals() method in C#...