Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
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.