Home »
.Net »
C# Programs
Demonstrate the example of IndexOf() method of string class in C#
String.IndexOf() method in C#: Here, we will learn with an example, how to find index of a substring in a string? Its returns index of first character exists in the string.
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.
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
C# Basic Programs »