This documentation is archived and is not being maintained.

Code: Searching Within a String (Visual C#)

Visual Studio .NET 2003

This example calls the IndexOf method on a String object to report the index of the first occurrence of a substring.


string searchWithinThis = "ABCDEFGHIJKLMNOP";
string searchForThis = "DEF";
int firstCharacter = searchWithinThis.IndexOf(searchForThis);

Console.WriteLine("First occurrence: {0}", firstCharacter);

Compiling the Code

Copy the code and paste it into the Main method of a console application.

Robust Programming

The IndexOf method reports the location of the first character of the first occurrence of the substring. The index is 0-based, which means the first character of a string has an index of 0.

If IndexOf does not find the substring, it returns -1.

The IndexOf method is case-sensitive and uses the current culture.

If you want more control over possible exceptions, enclose the string search in a try-catch statement.

See Also

Exception Handling Statements| string | String.IndexOf Method (String) | General Language Example Topics