概要
指定された配列の指定された範囲についてある特定の要素が何番目にあるか検索をする。調べる要素が配列に複数含まれていたら最も小さい番号を返す。
次の表はその種類を示したものである。
関数 | 説明 |
---|---|
public static int IndexOf(Array array, object value) | 一番基本的なもの valueの値が配列arrayの何番目の要素かを返す。 配列内に複数のvalueが存在する場合は先頭の位置を返す。 valueが含まれていない、または-arrayの要素の型とvalueの型が違うと1が返ってくる。 |
public static int IndexOf(Array array, object value, int startIndex) | arrayのstartIndex番目の要素から配列の末尾にかけて同様の検索を行う |
public static int IndexOf(Array array, object value, int startIndex, int count) | starIndex番目の要素からcount個だけ同様の検索を行う。 配列の大きさを超えるとエラー |
使用例
public static int IndexOf(Array array, object value);
using System; public class Sample { public static void Main() { int[] a = new int[8] { 4, 3, 5, 1, 8, 9, 10, 5 }; Console.WriteLine(Array.IndexOf(a, 5)); Console.WriteLine(Array.IndexOf(a, -2)); Console.WriteLine(Array.IndexOf(a, "5")); } }
//実行結果 2 -1 -1
public static int IndexOf(Array array, object value, int startIndex);
//処理 using System; public class Sample { public static void Main() { int[] a = new int[8] { 4, 3, 5, 1, 8, 9, 10, 5 }; Console.WriteLine(Array.IndexOf(a, 5, 2)); Console.WriteLine(Array.IndexOf(a, 5, 3)); Console.WriteLine(Array.IndexOf(a, 4, 3)); } }
//実行結果 2 7 -1
public static int IndexOf(Array array, object value, int startIndex, int count
using System; public class Sample { public static void Main() { int[] a = new int[8] { 4, 3, 5, 1, 8, 9, 10, 5 }; Console.WriteLine(Array.IndexOf(a, 5, 1, 1)); Console.WriteLine(Array.IndexOf(a, 5, 1, 2)); Console.WriteLine(Array.IndexOf(a, 5, 6, 2)); Console.WriteLine(Array.IndexOf(a, 5, 3, 4)); } }
//実行結果 -1 2 7 -1