System.String.IndexOf Method

Reports the zero-based index of the first occurrence of the specified string in this instance.

Syntax

public int IndexOf (string value)

Parameters

value
The string to seek.

Returns

The zero-based index position of value if that string is found, or -1 if it is not. If value is string.Empty, the return value is 0.

Exceptions

TypeReason
ArgumentNullException value is a null reference.

Remarks

Index numbering starts from zero.

This method performs a word (case-sensitive and culture-sensitive) search using the current culture. The search begins at the first character position of this instance and continues until the last character position.

Character sets include ignorable characters, which are characters that are not considered when performing a linguistic or culture-sensitive comparison. In a culture-sensitive search, if value contains an ignorable character, the result is equivalent to searching with that character removed. If value consists only of one or more ignorable characters, the string.IndexOf(string) method always returns 0 (zero) to indicate that the match is found at the beginning of the current instance. In the following example, the string.IndexOf(string) method is used to find three substrings (a soft hyphen (U+00AD), a soft hyphen followed by "n", and a soft hyphen followed by "m") in two strings. Only one of the strings contains a soft hyphen. In each case, because the soft hyphen is an ignorable character, the result is the same as if the soft hyphen had not been included in value. When searching for a soft hyphen only, the method returns 0 (zero) to indicate that it has found a match at the beginning of the string.

code reference: System.String.IndexOf#21

Example

The following example demonstrates the string.IndexOf(char) method.

C# Example

using System;
public class StringIndexOf {
 public static void Main() {
 String str = "This is the string";
 Console.WriteLine( "Searching for the index of \"is\" yields {0,2}.", str.IndexOf( "is" ) );
 Console.WriteLine( "Searching for the index of \"Is\" yields {0,2}.", str.IndexOf( "Is" ) );
 Console.WriteLine( "Searching for the index of \"\" yields {0,2}.", str.IndexOf( "" ) );
 }
}

The output is

Searching for the index of "is" yields 2.
Searching for the index of "Is" yields -1.
Searching for the index of "" yields 0.

Requirements

Namespace: System
Assembly: mscorlib (in mscorlib.dll)
Assembly Versions: 1.0.5000.0, 2.0.0.0, 4.0.0.0