![]() |
VOOZH | about |
In C#, the IndexOf() method is a String method. Used to find the zero-based index of the first occurrence of a specified character or string within the current instance of the string. The method returns -1 if the character or string is not found. This method can be overloaded by passing different parameters to it.
This method returns the zero-based index of the first occurrence of the specified character within the string. In case no such character is found then it returns -1.
Syntax:
public int IndexOf(char x)
Example: In the below code, the User wants to know the index of character ‘F’ within the specified string “GeeksForGeeks”
The Index Value of character 'F': 5 The Index Value of character 'C' is -1
This method returns the zero-based index of the first occurrence of the specified character within the string. However, the search for that character will start from a specified position and if not found it returns -1.
Syntax:
public int IndexOf(char x, int start1)
Example: This example aims to find the index of character 'H' in the string "HelloGeeks".
The Index Value of character 'H' with start index 0 is 0 The Index Value of character 'H' is -1
This method returns the zero-based index of the first occurrence of the specified character within the string. However, the search of that character will start from a specified position start1 till specified position i.e start2 and if not found it returns -1.
Syntax:
public int IndexOf(char x, int start1, int start2)
Example: This example demonstrates how to find the character within a string using string indexOf(char x, int start1, int start2).
Index Value of 'f' with start Index = 2 and end Index = 14 is 11 Index Value of 'f' with start Index = 1 and end Index = 8 is -1
Explanation: In the above example, we want to know the index of character ‘f’ within the specified string “Hello Geeks for Geeks” and as a result, this method returns the index value of character ‘f’. Again for the case where start1 > 1 and start2 < 8. Then it returns -1 because it didn’t find any character.
This method returns the zero-based index of the first occurrence of the specified sub-string within the string. In case no such string is found then it returns -1 same as in the case of characters.
Syntax:
public int IndexOf(string s1)
Example: This example demonstrates the use of String.IndexOf(string s1) to find the index of a substring in a specified string.
First value Index of 'How' is 17 First value Index of 'Chair' is -1
Explanation: In the above example, the string ‘How’ is present in the main string, so it will simply return the index value of its first character. However, in the next case, there is no substring with the name “Chair” so, it simply returns -1.