Welcome to the new DelphiDabbler Code Library Documentation.

This is a new site that's currently running on alpha code. There are going to be bugs. If you discover any, please report them on the site's issues page (GitHub account required). Thanks.

Warning: Many URLs are going to change. Refer to the README file to discover which library project's documentation has been completed.

Slice<T> class method

Project: Array Utilities Unit

Unit: DelphiDabbler.Lib.ArrayUtils

Record: TArrayUtils

Applies to: ~>0.1

class function Slice<T>(const A: array of T;
  AStartIndex, AEndIndex: Integer): TArray<T>;
  overload; static;

class function Slice<T>(const A: array of T;
  AStartIndex: Integer): TArray<T>;
  overload; static;

Description

Returns an array comprising a contiguous range of elements from an array.

The elements of the returned array are shallow copies of the corresponding elements of the original array, so any references within the resulting array are the same as those in the initial array.

The original array is not modified.

Parameters:

Returns:

Note

If the returned array needs to have deep copies of the the original array elements then pass the return value of Slice<T> to the deep copying overload of Copy<T>, along with a suitable TCloner<T> implementation.

Examples

Example #1

This example shows the most flexible use of Slice<T> where both the start and end indexes are provided:

procedure Slice_Eg1;
var
  A, ASlice, AExpectedSlice: TArray<string>;
begin
  A := TArray<string>.Create('a', 'stitch', 'in', 'time', 'saves', 'nine');
  // slice from the start of A
  ASlice := TArrayUtils.Slice<string>(A, 0, 2);
  AExpectedSlice := TArray<string>.Create('a', 'stitch', 'in');
  Assert(TArrayUtils.Equal<string>(AExpectedSlice, ASlice, SameStr));
  // slice in the middle of A
  ASlice := TArrayUtils.Slice<string>(A, 2, 4);
  AExpectedSlice := TArray<string>.Create('in', 'time', 'saves');
  Assert(TArrayUtils.Equal<string>(AExpectedSlice, ASlice, SameStr));
  // slice at the end of A
  ASlice := TArrayUtils.Slice<string>(A, 4, 5);
  AExpectedSlice := TArray<string>.Create('saves', 'nine');
  Assert(TArrayUtils.Equal<string>(AExpectedSlice, ASlice, SameStr));
end;

Example #2

This second example show the use of the basic version of Slice<T> where only the start index is provided:

procedure Slice_Eg2;
var
  A, ASlice, AExpectedSlice: TArray<string>;
begin
  A := TArray<string>.Create('a', 'stitch', 'in', 'time', 'saves', 'nine');
  // slice from mid to end of A
  ASlice := TArrayUtils.Slice<string>(A, 3);
  AExpectedSlice := TArray<string>.Create('time', 'saves', 'nine');
  Assert(TArrayUtils.Equal<string>(AExpectedSlice, ASlice, SameStr));
  // slice of all of A
  ASlice := TArrayUtils.Slice<string>(A, 0);
  AExpectedSlice := A;
  Assert(TArrayUtils.Equal<string>(AExpectedSlice, ASlice, SameStr));
end;

See Also