This post will discuss how to extract the first few characters of a string in C#.

1. Using String.Substring() method

To extract the first n characters from the end of a string, you can use the String.Substring() method. The idea is to pass the starting index as 0 and the ending index as n. However, this would throw an ArgumentOutOfRangeException if the input string’s length is less than the number of characters to be removed. Therefore, you should ensure that the ending index is less than the string length.

Download  Run Code

2. Using C# 8 Ranges

Starting with C# 8, you can use the ranges .. to extract characters from the start of a string. It takes the start and end of a range as its operands. To avoid ArgumentOutOfRangeException when the input string’s length is less than the required length, you can use the Math.Min() method to determine the ending index.

Download  Run Code

 
The above solution can be further shortened using the null-conditional operator ?. This eliminates the need for an explicit null check.

Download  Run Code

3. Using Enumerable.Take() method

If you are allowed to use LINQ, you can use the Take() method. It returns a specified number of contiguous elements from the start of a sequence. We can use it with the String constructor, which takes an IEnumerable<T> to construct a new instance of the string. Note that you need to include the System.Linq namespace.

Download  Run Code

That’s all about extracting the first few characters of a string in C#.