Learnerslesson
   JAVA   
  SPRING  
  SPRINGBOOT  
 HIBERNATE 
  HADOOP  
   HIVE   
   ALGORITHMS   
   PYTHON   
   GO   
   KOTLIN   
   C#   
   RUBY   
   C++   




IndexOf() - Method


IndexOf() Method


The IndexOf() Method is used to find a substring from the String. It gives us the position of the substring.


Example :



public class MyApplication
{
    public static void Main(string[] args)
    {
        string x = "Hello Beautiful World";
	    int y = x.IndexOf("Beautiful");

        System.Console.WriteLine("The substring is located at the position "+y); 
    }
}


Output :



  The substring is located at the position 6

In the above code, we have declared a String Hello Beautiful World and assigned it to a variable x.


string x = "Hello Beautiful World";
C_Sharp


And we would be searching the substring Beautiful, from the String, Hello Beautiful World.


So, we have used the IndexOf() Method to find the substring Beautiful.


int y = x.IndexOf("Beautiful");

And what IndexOf() Method does is, goes to the String Hello Beautiful World and searches for the position of the substring Beautiful.

C_Sharp

And finds the substring Beautiful in the 6th position. And the position (i.e. 6) is stored in variable y.

C_Sharp

And thus prints the position.


System.Console.WriteLine("The substring is located at the position "+y);

Output :



  The substring is located at the position 6


Now, let us say you have the below String,


"Hello Beautiful World"

And you have to search for the substring Care.


Off course the substring Care is not present in the String, "Hello Beautiful World".


Example :



public class MyApplication
{
    public static void Main(string[] args)
    {
        string x = "Hello Beautiful World";
	    int y = x.IndexOf("Care");

        System.Console.WriteLine("The substring is located at the position "+y); 
    }
}  


Output :



  The substring is located at the position -1

So, if you see the above output, it says -1.


Little Weird! Right?


Well! -1 is returned because the substring Care is not present in the String, "Hello Beautiful World".


Just remember, if a substring is not found, -1 is returned.