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


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

Updated on: 22-Jun-2020

434 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements