Array search with IndexOf methods
In this chapter you will learn:
Use IndexOf and LastIndexOf methods
using System;//j av a2 s. c o m
class MainClass
{
public static void Main()
{
string[] stringArray = {"Hello", "to", "everyone", "Hello", "all"};
Console.WriteLine("stringArray:");
for (int i = 0; i < stringArray.Length; i++)
{
Console.WriteLine("stringArray[" + i + "] = " + stringArray[i]);
}
int index = Array.IndexOf(stringArray, "Hello");
Console.WriteLine("Array.IndexOf(stringArray, \"Hello\") = " + index);
index = Array.LastIndexOf(stringArray, "Hello");
Console.WriteLine("Array.LastIndexOf(stringArray, \"Hello\") = " + index);
}
}
The code above generates the following result.
Search index of int array
using System;/*j av a 2s . c o m*/
class MainClass
{
public static void Main()
{
int[] intArray = {1, 2, 1, 3};
Console.WriteLine("intArray:");
for (int i = 0; i < intArray.Length; i++)
{
Console.WriteLine("intArray[" + i + "] = " +
intArray[i]);
}
int index = Array.IndexOf(intArray, 1);
Console.WriteLine("Array.IndexOf(intArray, 1) = " + index);
index = Array.LastIndexOf(intArray, 1);
Console.WriteLine("Array.LastIndexOf(intArray, 1) = " + index);
}
}
The code above generates the following result.
Next chapter...
What you will learn in the next chapter:
- Use the BinarySearch() method to search int Array for the number 5
- BinarySearch() returns a negative value in case of not found
- Binary search array element
- Use the BinarySearch() method to search charArray for 'o'
Home » C# Tutorial » Array