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

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


ประกาศและเริ่มต้นอาร์เรย์ -

string[] str = new string[] {
   "Cat",
   "Mat",
   "Rat"
};

ตอนนี้ ue IndexOf() วิธีการหาดัชนีของคำว่า “เสื่อ” −

Array.IndexOf(str, "Mat");

ต่อไปนี้เป็นรหัส −

ตัวอย่าง

using System;

public class Demo {
   public static void Main() {
      string[] str = new string[] {
         "Cat",
         "Mat",
         "Rat"
      };
      Console.WriteLine("Our Array =");
      for (int i = 0; i < str.Length; i++) {
         string res = str[i];
         Console.WriteLine(res);
      }
      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