Input and output. The key thing to remember with slice is that the second argument is an end index, not a length. And we can use a negative end index to count from the end.
Slice(1, 4) Peaceful eac
Slice(3, -2) The morning is upon us. morning is upon u
And The second parameter can be any integer. When it is negative, it means you start from the end and then count backwards.
Info The first character of the second test, which is similar to the Mozilla test, shows the first character as a space.
Detail My interpretation is that this is correct—the space is at index 3, while "m" is index 4.
static void Main()
//// Tests from Mozilla//
Console.WriteLine("The morning is upon us.".Slice(3, -2));
// " morning is upon u"
string s = "0123456789_";
//// These slices are valid://
Console.WriteLine(s.Slice(0, 1)); // First char
Console.WriteLine(s.Slice(0, 2)); // First two chars
Console.WriteLine(s.Slice(1, 2)); // Second char
Console.WriteLine(s.Slice(8, 11)); // Last three chars
public static class Extensions
/// <summary>/// Get the string slice between the two indexes./// Inclusive for start index, exclusive for end index./// </summary>
public static string Slice(this string source, int start, int end)
if (end < 0) // Keep this for negative end support
end = source.Length + end;
int len = end - start; // Calculate length
return source.Substring(start, len); // Return Substring of length
morning is upon u
Extension notes. This is an extension method. To create an extension method, use the "this" keyword as the first parameter in a static method (in a static class).