C# | String IndexOf()

In this post we will learn about C# | String IndexOf() method with the help of examples. How it works – it searches the string from the start to the end. IndexOf() method in C# searches one given string for another. If one is found, it returns the index of the string part where given string is located.

Main use of this method is to confirm that given string is present in the main string or not. If it is present, then at what location/index it is present.

using System;  
  class StringTest {
    public static void Main(string [] args) {
     
      string str = "Code config tutorial website is for those who want to learn Dot Net, C#, VB.net";

      // returns index of substring cream
      int final= str.IndexOf("C#");
    
      Console.WriteLine(final);   
      Console.ReadLine();    
    }
  } 

Output

C# | String IndexOf()

String.LastIndexOf()

LastIndexOf() method works like IndexOf, but searches in reverse order, from the right to the left part of the string. It starts with the last char and returns the index of the string/char available at the end means after this there is no occurrence of this word i.e., towards right side.

using System;  
  class StringTest
 {
    public static void Main(string [] args) 
   {
             var data = "Rakesh_code_Config_?";
             // Find last underscore feom left to right side.
              int final = data.LastIndexOf('_');
             if (final != -1)
             {
               Console.WriteLine("Last underscore is at {0}", final);
             } 
    }
  } 

You can check our website’s C# Section for more such information.

You may like

Leave a Reply

Your email address will not be published. Required fields are marked *