What is String.IndexOf() in C#?

Overview

In C#, the String.IndexOf() is a string method used to find the location of a character or substring within the String object.

Syntax

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 object
String.IndexOf(char ch, int startIndex);
// find the location of a substring
// within a string object
String.IndexOf(string substring, int startIndex);
syntax for IndexOf() method

Parameters

  • 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.

Return value

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.

Exception

  • 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.

Example

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 examples
public static void Main() {
string str = "this is a string example";
Console.WriteLine(str.IndexOf('a'));
}
}

Explanation

  • Line 7: First, we create a string variable str to hold our source string.
  • Line 8: Next, we'll call the 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.

Free Resources