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 thestr.
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 methodstatic void Main(){// create our stringsstring str1 = "Hello";string str2 = "World";string str3 = "This is";string str4 = "Edpresso!";// get index of some characters// in the strings aboveint ind1 = str1.IndexOf("H");int ind2 = str2.IndexOf("w");int ind3 = str3.IndexOf("a");int ind4 = str4.IndexOf("!");// print out returned valuesSystem.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
indexOfmethod to find the indexes ofH,w,a, and!instr1,str2,str3, andstr4, respectively. -
Lines 20–23: We display the indexes on the console.
ind2andind3return-1becausewandaare not found in theWorldandThis isstrings, respectively.