Determine index of a character in a string in C#
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
using System; public class Example { public static void Main() { string input = "Hello, World"; char c = ','; int index = input.IndexOf(c); Console.WriteLine("Index of character '{0}' is {1}", c, index); } } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
using System; public class Example { public static void Main() { string input = "Hello, World"; string s = "World"; int index = input.IndexOf(s); Console.WriteLine("Index of substring \"{0}\" is {1}", s, index); } } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
using System; public class Example { public static void Main() { string input = "A,B,C"; char c = ','; int lastIndex = input.LastIndexOf(c); Console.WriteLine("The last index of character '{0}' is {1}", c, lastIndex); } } |
Output:
The last index of character ‘,’ is 3
That’s all about determining the index of a character in a string in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)