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)];