Cut a string with a known start & end index

If endIndex points to the last character that you want to have included in the extracted substring:

int length = endIndex - startIndex + 1;
string extracted = s.Substring(startIndex, length);

If endIndex points to the first character following the desired substring (i.e. to the start of the remaining text):

int length = endIndex - startIndex;
string extracted = s.Substring(startIndex, length);

See String.Substring Method (Int32, Int32) for the official description on Microsoft Docs.


Since C# 8.0, in .NET Core and .NET 5+ only, you can use Indices and ranges

string extracted = s[startIndex..endIndex];

where the position at endIndex is excluded. This corresponds to my second example with Substring where endIndex points to the first character following the desired substring (i.e. to the start of the remaining text).

If endIndex is intended to point to the last character that you want to have included, just add one to endIndex:

string extracted = s[startIndex..(endIndex + 1)];

This becomes possible with the new Range feature of C# 8.0.

An extension method on string that uses Range to achieve this is:

public static class StringExtensions
{
    public static string SubstringByIndexes(this string value, int startIndex, int endIndex)
    {
        var r = Range.Create(startIndex, endIndex + 1);
        return value[r];
        /*
        // The content of this method can be simplified down to:

        return value[startIndex..endIndex + 1];

        // by using a 'Range Expression' instead of constructing the Range 'long hand'
        */
    }
}

Note: 1 is added to endIndex when constructing the Range that's used as the end of the range is exclusive, rather than inclusive.

Which can be called like this:

var someText = "ABCDEFG";

var substring = someText.SubstringByIndexes(1, 3);

Giving a value of BCD in substring.

Tags:

C#

String