C# program to find the index of a word in a string

CsharpProgrammingServer Side Programming

Declare and initialize an array −

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

Now, ue IndexOf() method to find the index of the word “Mat” −

Array.IndexOf(str, "Mat");

The following is the code −

Example

 Live Demo

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);
   }
}

Output

Our Array =
Cat
Mat
Rat
Element Mat found at the following index: 1
raja
Published on 04-Sep-2018 08:28:18
Advertisements