C# - String.IndexOf() Method with Example

String.IndexOf() method in C#: Given a string and we have find the index of a substring.
[Last updated : March 20, 2023]

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);

Return Value

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.

C# program to demonstrate the example of String.IndexOf() 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.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

C# Basic Programs »

Comments and Discussions!

Load comments ↻





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