Updated on

The fastest way to get the first N characters of a string in C# is a span, AsSpan(0, n) or AsSpan()[..n], because it copies nothing. When we need a new string, the range operator text[..n] or Substring(0, n) does the job. Both of them throw an exception if the string is shorter than N.

We will start by creating an input string. Then, we will define and explain different methods that we can utilize to accomplish this task. At the end, we will use the BenchmarkDotNet library to compare and rank the performances of these methods.

To download the source code for this article, you can visit our GitHub repository.

Alright, let’s dive in.

Set Up the Environment

Before we explore our methods, let’s define our input string and the number of characters we want to retrieve:

public class FirstNCharactersOfStringGetter(string inputString = "CodeMaze", int numberOfCharacters = 4)
{
}

In this primary constructor, we define our input string and the number of characters we want to obtain from it as optional parameters. We set the default value of our string to "CodeMaze" and specify that the default number of characters we wish to retrieve as 4.

Now, for most of the methods that we will implement, attempting to retrieve more characters from a string than it contains will result in exceptions. Therefore, to avoid these exceptions, let’s define a method to check for this scenario:

private bool IsInputStringShorter()
    => inputString.Length < numberOfCharacters;

In this method, we check if our string is shorter than the number of characters we intend to retrieve. If it is, this method returns true. If we want to cut a string down to a maximum length instead, our article on how to truncate a string in C# builds its helper around the same length check.

Different Methods to Get the First N Characters of a String

Now, with our setup complete, let’s implement eight methods to get the first N characters of a string. Most of our methods use a ReadOnlySpan<char> as their return type, so the span-based ones can hand back their result without copying it. Therefore, when we return strings or arrays from these methods, they are implicitly converted to a ReadOnlySpan<char>. For an in-depth look at Span<T> and ReadOnlySpan<T>, be sure to check out our article on them.

Let’s now create and discuss some different methods to get the first N characters of a string. 

Use the Substring Method

First, let’s use the Substring() method:

public ReadOnlySpan<char> UseSubstring()
{
    if (IsInputStringShorter())
        return inputString;

    return inputString.Substring(0, numberOfCharacters);
}

As with the other methods, we start by checking that our string has enough characters.

Then, we pass two arguments to Substring(). The first one is the index where the substring starts, 0 in our case, and the second one is the number of characters we want. The Microsoft Learn page for String.Substring says the method “returns a new string with length characters starting from the startIndex position”. So, unless we ask for the whole string or for no characters, every call creates a new string, an allocation the span methods later on avoid.

Use the Range Operator on the String

Next, let’s use the range operator directly on our string:

public ReadOnlySpan<char> UseRangeOperator()
    => IsInputStringShorter()
    ? inputString
    : inputString[..numberOfCharacters];

The [..numberOfCharacters] range starts at the beginning of the string and stops before the index numberOfCharacters. This is the shortest way to write it, and it does the same work as the previous method. On a string, the compiler turns the range into a call to Substring(), so it creates a new string in the same cases.

We cover the operator itself in our article on ranges and indices.

Get the First N Characters of a String Using a for Loop

Next, let’s use a for loop to retrieve the first N characters of our string:

public ReadOnlySpan<char> UseForLoop()
{
    if (IsInputStringShorter())
        return inputString;

    var dest = new char[numberOfCharacters];
    for (int i = 0; i < numberOfCharacters; i++)
    {
        dest[i] = inputString[i];
    }

    return dest;
}

Here, we start by checking if the length of our string is less than the number of characters we want to obtain. If it is, we return the string without performing any operation.

However, if the length of our string is sufficient, we use a for loop to get the first N characters. We start this process by creating a character array that has the number of characters we want to retrieve as its size. Then, in our loop, we iterate over our input string and add its characters to our array until we reach the specified length.

Finally, we return the array.

Utilize the Remove Method

Next up, let’s use the Remove() method:

public ReadOnlySpan<char> UseRemove()
{
    if (IsInputStringShorter())
        return inputString;

    return inputString.Remove(numberOfCharacters);
}

Again, we first check to ensure that our string has enough characters.

If it does, then we invoke the Remove() method on the string. This method returns a string that is equivalent to our input string minus all the characters starting from the numberOfCharacters index until the end of the string.

Use the AsSpan Method to Get the First N Characters of a String

Moving forward, let’s discuss how to utilize the AsSpan() method to perform this task:

public ReadOnlySpan<char> UseAsSpan()
{
    if (IsInputStringShorter())
        return inputString;

    return inputString.AsSpan(0, numberOfCharacters);
}

Once again, we invoke our IsInputStringShorter() method to check if our string has enough characters.

If the string meets this criteria, we use the AsSpan() method to create a ReadOnlySpan<char> over a portion of our string, without copying any characters. The two arguments we provide to the AsSpan() method, denote the index where our ReadOnlySpan slice should start and its length.

For example, if we use the default value of our numberOfCharacters parameter, which is 4, the AsSpan() method will create a ReadOnlySpan that contains the first four characters of our string.

Get the First N Characters of a String Using the AsSpan Method with a Range Operator

Now, let’s use the AsSpan() method differently.

Let’s see how we can convert our entire string to a ReadOnlySpan<char> and then extract the characters we want:

public ReadOnlySpan<char> UseAsSpanWithRangeOperator()
    => IsInputStringShorter()
    ? inputString
    : inputString.AsSpan()[..numberOfCharacters];

This time, we use the ternary operator instead of an if-else statement. We begin by checking if our string is shorter than the desired number of characters. If it is, we return the original string.

Otherwise, we call the AsSpan() method to wrap our string in a ReadOnlySpan<char> and utilize the range operator to get the characters we want. Specifically, we use the [..numberOfCharacters] operator to extract characters from the beginning of our ReadOnlySpan up to the character at the index numberOfCharacters - 1.

Get the First N Characters of a String With LINQ

Next, let’s use a LINQ method to carry out this task:

public IEnumerable<char> UseLINQEnumerable()
    => inputString.Take(numberOfCharacters);

Here, we invoke the Take() method to get an IEnumerable<char> that contains our desired characters.

Note that we do not perform our length check in this method, because the Take() method stops when the string runs out of characters. If we ask for more characters than the string has, we get all of them.

Also, Take() gives us an IEnumerable<char>, not a string. Calling ToString() on it prints the iterator’s type name, so to get the text back we use string.Concat(inputString.Take(numberOfCharacters)).

Use the ToCharArray Method

Now, let’s talk about the ToCharArray() method:

public ReadOnlySpan<char> UseToCharArray()
{
    if (IsInputStringShorter())
        return inputString;

    return inputString.ToCharArray(0, numberOfCharacters);
}

For this approach, once again we begin by calling our IsInputStringShorter() method. If it returns true, we return the input string.

Otherwise, we pass two arguments to the ToCharArray() method and call it on our string. This method copies the number of characters we specify from our string into a char array. In our case, we want all the characters from the beginning of the string to the index numberOfCharacters - 1.

After that, we return the array.

What Happens When the String Is Shorter Than N Characters?

Every one of the eight approaches above except the LINQ one throws an exception when the string has fewer than N characters. Substring(0, n), text[..n], Remove(n), AsSpan(0, n), AsSpan()[..n] and ToCharArray(0, n) throw an ArgumentOutOfRangeException. A plain for loop throws an IndexOutOfRangeException as soon as it reads past the last character.

That is why each of our methods calls IsInputStringShorter() first. If the string is too short, we return it as it is.

Take(n) is the exception to the rule. It stops when the string runs out, so "Cod".Take(8) gives us the three characters we have and doesn’t throw.

If we want the same safety in one line, Math.Min() caps the count at the length of the string:

public string UseRangeWithMathMin()
    => inputString[..Math.Min(numberOfCharacters, inputString.Length)];

With "Cod" and a count of 8, this returns "Cod". With an empty string, it returns an empty string.

The Math.Min() line only caps the count. When the goal is to cut long text down to a maximum length, our article on how to truncate a string in C# goes further.

How Do We Get the First Character of a String in C#?

To get the first character of a string in C#, we use the indexer with [0]. It returns a char, not a string:

public char GetFirstCharacter()
    => inputString[0];

For "CodeMaze", this gives us 'C'.

When we need the first character as a string, the range operator does it: inputString[..1] returns "C". That is our earlier method with N set to 1.

Both forms fail on an empty string, each in its own way. [0] throws an IndexOutOfRangeException, and [..1] throws an ArgumentOutOfRangeException. So, if the string can be empty, we check inputString.Length > 0 first, or use string.IsNullOrEmpty() when it can also be null.

Also, .NET strings are made of UTF-16 code units, so “the first character” means the first char. For most text, that is the letter we see. But an emoji takes two char values, and [0] returns only the first half of it.

If what we really want is to upper-case that first letter, our article on capitalizing the first letter covers it.

Benchmarking Our Methods

Now that we have implemented all our methods, let’s compare their performance.

We use the BenchmarkDotNet library for this comparison. For more information on this library, please visit our article on benchmarking C# projects.

Of course, we already prepared the benchmark and you can find it in our source code linked in this article.

Besides our eight methods, the benchmark measures one more case. It takes the span from UseAsSpan() and turns it into a string, because that is the price we pay when the caller needs a real string:

[Benchmark]
public string UseAsSpanThenToString()
    => _firstNCharactersOfStringGetter.UseAsSpan().ToString();

The timings will differ on other machines and from run to run. Now, let’s check the results:

| Method                     | Mean       | Error     | StdDev    | Gen0   | Allocated |
|--------------------------- |-----------:|----------:|----------:|-------:|----------:|
| UseAsSpanWithRangeOperator |  0.8135 ns | 0.0484 ns | 0.1021 ns |      - |         - |
| UseAsSpan                  |  0.9745 ns | 0.0406 ns | 0.0360 ns |      - |         - |
| UseForLoop                 |  8.0849 ns | 0.1908 ns | 0.3897 ns | 0.0038 |      32 B |
| UseSubstring               |  8.4449 ns | 0.2698 ns | 0.7871 ns | 0.0038 |      32 B |
| UseRemove                  |  8.5524 ns | 0.2030 ns | 0.4902 ns | 0.0038 |      32 B |
| UseRangeOperator           |  8.5969 ns | 0.3417 ns | 0.9914 ns | 0.0038 |      32 B |
| UseToCharArray             |  9.3552 ns | 0.3749 ns | 1.0937 ns | 0.0038 |      32 B |
| UseAsSpanThenToString      | 11.1066 ns | 0.3772 ns | 1.0763 ns | 0.0038 |      32 B |
| UseLINQEnumerable          | 30.3493 ns | 0.6344 ns | 1.7894 ns | 0.0105 |      88 B |

As we can see from these results, using the AsSpan() method that wraps our entire string in a ReadOnlySpan and then slices the characters we want from that span is, in our run, the fastest way to get the first N characters of a string in C#.

In the second place, we see the AsSpan() method that creates a ReadOnlySpan that contains only our desired characters. Both take less than a nanosecond, and the gap between them is less than two tenths of a nanosecond. Their order can swap from one run to the next.

From the results, it’s also evident that the top two methods are the methods that create a span from our string. In addition to their fast execution speed, these methods do not allocate any memory. We also do not perform any garbage collection during their operation.

A span copies nothing. It points at the memory of our original string, which is why it is so fast and also why we can’t keep it everywhere. For example, the compiler won’t let us store a ReadOnlySpan<char> in a field of a class and stops us with error CS8345. When we need the result as a string, we call ToString(), and the UseAsSpanThenToString() row shows what that costs: the same 32 bytes as Substring(), and it is no longer among the fastest rows.

After these methods, we have the UseForLoop(), UseSubstring(), UseRemove(), UseRangeOperator() and UseToCharArray() methods. These methods allocate managed memory, which leads to garbage collection. Their timings are close, all between 8 and 10 nanoseconds in our run, so when we need a new string or array, any of them will do.

Finally, the slowest way to get the first N characters of a string is by using LINQ. Even though we avoid the initial length check in this method, it displays the longest execution time. It also allocates the most memory. Take() creates an iterator object, and reading through it creates one more, an enumerator over the string, before we get a single character.

Here is every approach from this article side by side, with what it returns and what it does when the string is too short:

ApproachReturnsNew allocationString shorter than N
Substring()stringYes, unless N is 0 or covers the whole stringThrows ArgumentOutOfRangeException
Range operatorstringYes, unless N is 0 or covers the whole stringThrows ArgumentOutOfRangeException
Remove()stringYes, unless N is 0 or covers the whole stringThrows ArgumentOutOfRangeException
AsSpan()ReadOnlySpan<char>NoThrows ArgumentOutOfRangeException
AsSpan() with a rangeReadOnlySpan<char>NoThrows ArgumentOutOfRangeException
ToCharArray()char[]Yes, unless N is 0Throws ArgumentOutOfRangeException
for loopchar[]Yes, a new arrayThrows IndexOutOfRangeException
LINQ Take()IEnumerable<char>Yes, an iteratorReturns all the characters
Range with Math.Min()stringYes, unless N is 0 or covers the whole stringReturns the whole string

If we only need to read the characters, a span is the fastest choice. When we need a string, the range operator is the shortest way to write it, and Math.Min() keeps it safe on a short string.

Conclusion

In this article, we have determined the fastest way to get the First N characters of a string.

First, we implemented and discussed eight different methods to perform this task. Then, we compared the performances of these methods using the BenchmarkDotNet library.

From the benchmark results, we concluded that using AsSpan() to get a ReadOnlySpan of our desired characters is the fastest way to get the first N characters of a string in C#.

When we need a string instead, the range operator [..n] and Substring() compile to the same call, so we can pick the one that reads better in our code. And if we need to work on the other end of a string, our article on how to remove the last character compares the same kinds of methods.

Tested with .NET 11.0.0, BenchmarkDotNet 0.15.8 and xUnit 2.9.3.