Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

โปรแกรม C# หาดัชนีของคำในอาร์เรย์สตริง


ภาพรวม

ใช้ Array.IndexOf() หา ดัชนีแรก ของค่าที่ระบุในอาร์เรย์ คืน -1 หากไม่พบ

รูปแบบการใช้งาน

string[] str = { "Cat", "Mat", "Rat" };
int index = Array.IndexOf(str, "Mat"); // 1

ตัวอย่างโค้ดเต็ม

using System;

public class Demo
{
    public static void Main()
    {
        string[] str = { "Cat", "Mat", "Rat" };
        Console.WriteLine("Our Array =");
        foreach (string s in str) Console.WriteLine(s);
        int findIndex = Array.IndexOf(str, "Mat");
        Console.Write("Element Mat found at the following index: ");
        Console.WriteLine(findIndex);
    }
}

ผลลัพธ์

Our Array =
Cat
Mat
Rat
Element Mat found at the following index: 1

เมธอดที่เกี่ยวข้อง

  • Array.LastIndexOf - หาดัชนีสุดท้าย
  • Array.BinarySearch - ค้นหาเร็ว (ต้องจัดเรียง)
  • List<T>.IndexOf - สำหรับ List
  • Array.FindIndex(predicate) - หาดัชนีแรกที่ตรงเงื่อนไข