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

Explore More

Working With File Class In C#

In C#, ‘File’ class provides many static methods for moving, copying, and deleting files. These Static methods involve moving a file and copying and deleting a file also. Let’s check

How to Read a Text File in C#

In C# ‘File’ class provides static methods to read given text file data. The File.ReadAllText() method opens a text file, reads all the text present in the file into a

C# | How to use Interface references

In C#, you’re permitted to make a reference variable of an interface type or in other words, you’re permitted to form an interface reference variable. Such kind of variable can