Q:

Demonstrate the example of IndexOf() method of string class in C#

belongs to collection: C# Basic Programs | String programs

0

Given a string and we have find the index of a substring.

String.IndexOf() method

It is a method of string class, which returns the first index (first occurrence) of the character in a string.

Syntax:

int String.IndexOf(String str);

This method returns integer value; it returns the index when sub-string found in string. If sub-string is not found in string then it returns negative value.

 

All Answers

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

Example of String.IndexOf() in C#

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.IndexOf(str2);

            if (index < 0)
                Console.WriteLine("Sub string is not find in string");
            else
                Console.WriteLine("Index str2 in str1 is: "+index);
        }
    }
  
}

Output

Enter string : Hello, How are you?
Enter sub string : How
Index str2 in str1 is: 7

 

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
Compare strings using Equals() method in C#... >>
<< Demonstrate the example of Copy method of String c...