This post will discuss how to determine the index of a character in a string in C#.

The standard solution to find the position of a character in a string is using the String.IndexOf() method. It returns the index of the first occurrence of the specified character within the string, and returns -1 if the character is not found. The following example demonstrates its usage.

Download  Run Code

Output:

Index of character ‘,’ is 5

 
Note that the IndexOf() method is overloaded for strings. Therefore, you can determine the index of the first occurrence of the specified string within your string.

Download  Run Code

Output:

Index of substring “World” is 7

 
If you need to find the position of the last occurrence of a character or string, consider using the String.LastIndexOf() method.

Download  Run Code

Output:

The last index of character ‘,’ is 3

That’s all about determining the index of a character in a string in C#.