search for a string in a string array in csharp

To search for a string in a string array in C#, you can use the static Array.IndexOf() method. This method takes two arguments: the array you want to search and the string you want to find. It returns the index of the first occurrence of the string in the array, or -1 if the string is not found.

Here's an example:

main.cs
string[] myArray = { "apple", "banana", "cherry", "date" };
string searchString = "banana";

int index = Array.IndexOf(myArray, searchString);

if (index != -1)
{
    Console.WriteLine("The string \"{0}\" was found at index {1}.", searchString, index);
}
else
{
    Console.WriteLine("The string \"{0}\" was not found in the array.", searchString);
}
351 chars
14 lines

In this example, we define a string array called myArray that contains four elements. We then define a searchString variable and set it to "banana". We call Array.IndexOf(myArray, searchString) to search for "banana" in the array, and store the index of the first occurrence (which is 1) in the index variable.

We then check the value of index to see if the string was found (if it's not equal to -1). If the string was found, we use Console.WriteLine() to print a message indicating the index where the string was found. If the string was not found, we print a message indicating that fact.

gistlibby LogSnag