How to: Search Within a String

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

Example

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

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

Concepts

C# Language Primer

Reference

System.String

Other Resources

Visual C# Express