In C#, the String.IndexOf()
is a string method used to find the location of a character or substring within the String object.
There are multiple overloaded versions of the String.IndexOf()
method in C#. The most common syntaxes of this method are as follows:
// find the location of a character// within a string objectString.IndexOf(char ch, int startIndex);// find the location of a substring// within a string objectString.IndexOf(string substring, int startIndex);
char ch
: This is a character whose index position is to be found.string substring
: This is a string whose index position is to be found. int startIndex
: This is an optional parameter. It represents the starting position for the search. Its default value is 0. This method returns an integer corresponding to the zero-based index of the first occurrence of the specified string or character within this instance. If not found, it returns a value of -1.
ArgumentNullException
: This exception is thrown when the source string or character's index position is null. ArgumentOutOfRangeException
: This exception is thrown when the startIndex
parameter value is less than zero or greater than the length of the string. In the example below, we'll use the IndexOf
method to search for a particular character within a string.
using System;public class Example {//Main method starts execution of C# code examplespublic static void Main() {string str = "this is a string example";Console.WriteLine(str.IndexOf('a'));}}
str
to hold our source string.IndexOf
method, passing in the character we want to search for. In this case, we're looking for the character 'a'
within the string str
.The IndexOf
method will return the index of where that character was found. In this example, it would return 8
, since 'a'
appears at position 8
in string str
.