C# .IndexOf()

bitSolver07486's avatar
Published Apr 11, 2023
Contribute to Docs

The .IndexOf() method is a string method that returns the index of the first occurrence of a specified character or substring in a given string. If the character or substring is not found, it returns -1.

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn Microsoft's popular C# programming language, used to make websites, mobile apps, video games, VR, and more.
    • Beginner Friendly.
      15 hours

Syntax

IndexOf(char value);
IndexOf(string value);
IndexOf(char value, int startIndex);
IndexOf(string value, int startIndex);
IndexOf(string value, int startIndex, int count);
  • value : The substring or character to search for.
  • startIndex (optional): The index from where the search should start.
  • count (optional): Maximum number of characters to search.

Example

The following example uses the IndexOf() method to find the index of the first occurrence of the character “d” in the string “Codecademy docs”.

string str = "Codecademy docs";
int index = str.IndexOf('d');
Console.WriteLine("Index: " + index);

This example results in the following output:

Index: 2

Codebyte Example

The following codebyte is runnable and shows the usage of the .IndexOf() method on a string.

Code
Output
Loading...

All contributors

Contribute to Docs

Learn C# on Codecademy

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn Microsoft's popular C# programming language, used to make websites, mobile apps, video games, VR, and more.
    • Beginner Friendly.
      15 hours