Remove first character of a string in C#
This article illustrates the different techniques to remove the first character from a string in C#.
1. Using Range Operator
Starting from C# 8, we can use the range operator to remove the first character from a string in C#. The range operator takes the start and the end from a range as its operands, and can be used as follows to remove the first character from a string.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
using System; public class Example { public static void Main() { String s = "ABCD"; s = s[1..]; Console.WriteLine(s); // BCD } } |
2. Using String.Substring() method
Another option is to use the String.Substring() method, which can create a substring of a string starting from the second position till its end. The following code example shows how to use this option:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
using System; public class Example { public static void Main() { String s = "ABCD"; s = s.Substring(1); Console.WriteLine(s); // BCD } } |
3. Using String.TrimStart() method
Finally, you can use the String.TrimStart() method to remove all occurrences of a specific character from the beginning of a string. For example, the following code removes all instances of the dot character (.) from the start of a string.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
using System; public class Example { public static void Main() { String s = "..Hello"; s = s.TrimStart('.'); Console.WriteLine(s); // Hello } } |
4. Using String.Remove() method
However, if you need to remove only the first occurrence of a character from any position in the string, you can find its index and pass the index to the String.Remove() method. 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 s = "H..Hello"; int firstIdx = s.IndexOf('.'); s = s.Remove(firstIdx, 1); Console.WriteLine(s); // H.Hello } } |
That’s all about removing the first character of 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 :)