This repository has been archived by the owner on Feb 19, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathArrays.java
103 lines (97 loc) · 2.48 KB
/
Arrays.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
//
// Copyright 2016, Yahoo Inc.
// Copyrights licensed under the New BSD License.
// See the accompanying LICENSE file for terms.
//
// ## Stability: 0 - Unstable
package github.com.jminusminus.core;
public class Arrays {
// Appends to the given array the given string.
//
// Exmaple:
//
// ```java
// String[] a = new String[]{"a", "b"};
//
// String[] a = Arrays.append(a, "c");
// // returns a,b,c
// ```
public static String[] append(String[] a, String b) {
int len = a.length;
String[] c = new String[len + 1];
System.arraycopy(a, 0, c, 0, a.length);
c[len] = b;
return c;
}
// Appends to the given array the given array.
//
// Exmaple:
//
// ```java
// String[] a = new String[]{"a", "b"};
// String[] a = new String[]{"c", "d"};
//
// String[] a = Arrays.append(a, b);
// // returns a,b,c,d
// ```
public static String[] append(String[] a, String[] b) {
int len = a.length + b.length;
String[] c = new String[len];
System.arraycopy(a, 0, c, 0, a.length);
System.arraycopy(b, 0, c, a.length, b.length);
return c;
}
// Slice the given array upto and including `end`.
//
// Exmaple:
//
// ```java
// String[] a = new String[]{"a", "b", "c", "d"};
//
// String[] s = Arrays.slice(a, 3);
// // returns a,b,c
//
// String[] s = Arrays.slice(a, -2);
// // returns a,b
// ```
public static String[] slice(String[] a, int end) {
if (end < 0) {
end = a.length + end;
}
return Arrays.slice(a, 0, end);
}
// Slice the given array after `start` upto and including `end`.
//
// Exmaple:
//
// ```java
// String[] a = new String[]{"a", "b", "c", "d"};
//
// String[] s = Arrays.slice(a, 0, 4);
// // a,b,c,d
//
// String[] s = Arrays.slice(a, 1, 3);
// // b,c
//
// String[] s = Arrays.slice(a, 1, -1);
// // b,c
// ```
public static String[] slice(String[] a, int start, int end) {
int len = a.length;
if (start > len) {
return new String[0];
}
if (start < 0) {
start = 0;
}
if (end > len) {
end = len - 1;
}
if (end < 0) {
end = a.length + end;
}
String[] b = new String[end - start];
System.arraycopy(a, start, b, 0, b.length);
return b;
}
}