.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.
Looking to contribute?
- 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.