C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Function/Input/Output:
Slice(1,4) Peaceful eac
Slice(3,-2) The morning is upon us. morning is upon u
Note: In JavaScript you can omit the second parameter. To duplicate this, create an overload that uses Length - 1 as the second parameter.
Info: The first character of the second test, which is similar to the Mozilla test, shows the first character as a space.
Correct: My interpretation is that this is correct. The space is at index 3, while "m" is index 4.
C# program that slices strings
using System;
class Program
{
static void Main()
{
//
// Tests from Mozilla
//
Console.WriteLine("Peaceful".Slice(1, 4));
// eac
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
}
}
Output
eac
morning is upon u
0
01
1
89_
However: In some projects it would be better to use a normal static method. But Slice is useful enough to warrant an extension method.