C# 程式以在字串中查詢單詞的索引


宣告並初始化一個數組 -

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

現在,我們使用 IndexOf() 方法查詢單詞“Mat”的索引 -

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

更新於: 22-6-2020

507 次瀏覽

開啟你的 職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.