What is the indexOf() method in C#?

Overview

In C#, the IndexOf() method is used to get the index of the first occurrence of a specific character in a string.

Syntax

str.IndexOf(c)

Parameters

  • str: The string that is used to find the character.
  • c: The character is searched for in the str.

Return value

This method returns the index of the first occurrence of the character c in str. If the character is not found in the string, the IndexOf() method returns -1.

Code

class IndexFinder
{
// main method
static void Main()
{
// create our strings
string str1 = "Hello";
string str2 = "World";
string str3 = "This is";
string str4 = "Edpresso!";
// get index of some characters
// in the strings above
int ind1 = str1.IndexOf("H");
int ind2 = str2.IndexOf("w");
int ind3 = str3.IndexOf("a");
int ind4 = str4.IndexOf("!");
// print out returned values
System.Console.WriteLine(ind1);
System.Console.WriteLine(ind2);
System.Console.WriteLine(ind3);
System.Console.WriteLine(ind4);
}
}

Code explanation

  • Lines 7–10: We declare the strings.

  • Lines 14–17: We use the indexOf method to find the indexes of H, w, a, and ! in str1, str2, str3, and str4, respectively.

  • Lines 20–23: We display the indexes on the console. ind2 and ind3 return -1 because w and a are not found in the World and This is strings, respectively.

Free Resources