Log in / create account | Login with OpenID
DocForge
Programmer's Wiki

Array Slicing

From DocForge

Array Slicing is the ability to copy only parts of an array. Combined with array concatenation it allows the ability to treat arrays nearly as a linked list. Array slicing is easiest shown:

Digital Mars D

version(tango) {
    import tango.stdc.stdio;
} else {
    import std.stdc.stdio;
}
 
int main() {
    int[] arr=[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ];
 
    int[] brr=arr[0 .. 4 ];
 
    foreach(int i, j; brr)
        printf("brr[%d] = %d\n", i, j);
 
    return 0;
}

Will print out:

brr[0] = 1
brr[1] = 2
brr[2] = 3
brr[3] = 4
brr[4] = 5

In the Digital Mars D language, the .. operators, when inside an array index lookup, specially refer to a selection of the array. Used with array concatenation you can easily cut elements from an array - in place, even!

version(tango) {
    import tango.stdc.stdio;
} else {
    import std.stdc.stdio;
}
 
int main() {
    int[] arr=[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ];
 
    printf("before cutting element 4\n");
    foreach(int i, j; arr)
        printf("  arr[%d] = %d\n", i, j);
 
    arr=arr[0 .. 3]~arr[5 .. $-1];
 
    printf("\nafter cutting element 4\n");
    foreach(int i, j; arr)
        printf("  arr[%d] = %d\n", i, j);
 
    return 0;
}

This example will output the following:

before cutting element 4
  arr[0] = 1
  arr[1] = 2
  arr[2] = 3
  arr[3] = 4
  arr[4] = 5
  arr[5] = 6
  arr[6] = 7
  arr[7] = 8
  arr[8] = 9
  arr[9] = 10

after cutting element 4
  arr[0] = 1
  arr[1] = 2
  arr[2] = 3
  arr[3] = 4
  arr[4] = 6
  arr[5] = 7
  arr[6] = 8
  arr[7] = 9
  arr[8] = 10