Array Slice

From SwiftAPI

Jump to: navigation, search

Contents

C#

Template:API FUNCTION: csharp, System.Collections.Generic, List, GetRange

List<int> a = new List<int>() { 0, 1, 1, 2, 3, 5, 8, 13 };
int startIndex = 3;
int length = 4;
List<int> b = a.GetRange(startIndex, length);
// b == { 2, 3, 5, 8 }

Java

int[] a = { 0, 1, 1, 2, 3, 5, 8, 13 };
int startIndex = 3;
int length = 4;
int[] b = new int[length];
System.arraycopy(a, startIndex, b, 0, length);
// b == { 2, 3, 5, 8 }

JavaScript

developer.mozilla.org

var a = [0, 1, 1, 2, 3, 5, 8, 13];
var startIndex = 3;
var length = 4;
var b = a.slice(startIndex, startIndex + length);
// b == [2, 3, 5, 8]

Objective-C

developer.apple.com

- (NSArray *)subarrayWithRange:(NSRange)range
NSArray *a = @[@0, @1, @1, @2, @3, @5, @8, @13];
int startIndex = 3;
int length = 4;
NSArray *b = [a subarrayWithRange:NSMakeRange(startIndex, length)];
// b == [2, 3, 5, 8]

Perl

@a = (0, 1, 1, 2, 3, 5, 8, 13);
$startIndex = 3;
$length = 4;
@b = @a[$startIndex..($startIndex+$length-1)];
# @b == (2, 3, 5, 8)

PHP

php.net

array array_slice ( array $array , int $offset [, int $length [, bool $preserve_keys = false ]] )
$a = array(0, 1, 1, 2, 3, 5, 8, 13);
$startIndex = 3;
$length = 4;
$b = array_slice($a, $startIndex, $length);
// $b == array(2, 3, 5, 8)

Python

a = [0, 1, 1, 2, 3, 5, 8, 13]
startIndex = 3
length = 4
b = a[startIndex:startIndex+length]
# b == [2, 3, 5, 8]

Ruby

a = [0, 1, 1, 2, 3, 5, 8, 13]
startIndex = 3
length = 4
b = a[startIndex, length]
# b == [2, 3, 5, 8]

Swift

let a = [0, 1, 1, 2, 3, 5, 8, 13]
let startIndex = 3
let length = 4
let b = Array(a[startIndex ..< startIndex+length])
// b == [2, 3, 5, 8]
Personal tools