.IndexOf()
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
.
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.
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn C# on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Free course
Learn C#
Learn Microsoft's popular C# programming language, used to make websites, mobile apps, video games, VR, and more.Beginner Friendly23 hours