Home » .Net

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.


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");
                Console.WriteLine("Index str2 in str1 is: "+index);


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

Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.

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.