How to: Search for a String in an Array of Strings
This example calls the IndexOf method on an array of strings to report the string number and index of the first occurrence of a substring.
Example
string[] strArray = {"ABCDEFG", "HIJKLMNOP"};
string findThisString = "JKL";
int strNumber;
int strIndex = 0;
for (strNumber = 0; strNumber < strArray.Length; strNumber+)
{
strIndex = strArray[strNumber].IndexOf(findThisString);
if (strIndex >= 0)
break;
}
System.Console.WriteLine("String number: {0}\nString index: {1}",
strNumber, strIndex);
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.