In c#, the string IndexOf method is useful to return an index of the first occurrence of the specified character in the given string.
Generally, in c# the string IndexOf method will start searching for the specified character starting from the Zero position and return the first occurrence of the specified character in the given string.
If you want to change the specified character search starting position and to examine the only specified number of character positions in a string, then we can do it by specifying the required start position and number of character positions to search in the string IndexOf method.
Following is the pictorial representation of searching for a specified character position in the given string using the IndexOf() method in the c# programming language.
If you observe the above diagram, we are trying to get the character “s” position in the given string “Suresh Dasari” and it returned the position as 4.
In c#, the string IndexOf() method will perform a case-sensitive search to get the specified character position that’s the reason we got the result as 4 even the character “S” exists at the starting position 0.
Following is the syntax of defining a string IndexOf method to get the specified character position in the c# programming language.
If you observe syntaxes, the IndexOf method will return the index position of a specified character or a string in the given string and we can change the starting position of characters search and length of characters to search based on our requirements.
The string IndexOf method will return an index position of a specified character if that character is found. In case the specified character is not found, then it will return -1.
Following is the example of using the string IndexOf() method to return an index position of a specified character in the given string c# programming language.
If you observe the above example, we used an IndexOf() method to find the index position of a defined character in the string “Suresh Dasari” with multiple conditions.
When you execute the above c# program, you will get the result as shown below.
This is how you can use the string IndexOf() method to get the position of a specified character in a given string in the c# programming language.