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
|
// 写一个函数 InsertStringSlice() 将切片插入到另一个切片的指定位置。
package main
import "fmt"
func InsertIntSlice(src *[]int, dst *[]int, index int) {
newSlice := make([]int, len(*src)+len(*dst))
at := copy(newSlice, (*src)[:index])
at += copy(newSlice[at:], (*dst)[:])
copy(newSlice[at:], (*src)[index:])
//for i, v := range *src {
// newSlice[i] = v
//}
//for i := len(*src) + len(*dst) - 1; i >= index+len(*dst); i-- {
// newSlice[i] = newSlice[i-len(*dst)]
//}
//copy(newSlice[index:], *dst)
*src = newSlice
}
func InsertStringSlice(src *[]string, dst *[]string, index int) {
newSlice := make([]string, len(*src)+len(*dst))
at := copy(newSlice, (*src)[:index])
at += copy(newSlice[at:], (*dst)[:])
copy(newSlice[at:], (*src)[index:])
*src = newSlice
}
func main() {
src := []int{1, 2, 3, 4, 5, 6, 7, 8, 9}
dst := []int{12, 13}
InsertIntSlice(&src, &dst, 2)
fmt.Println(src)
s := []string{"M", "N", "O", "P", "Q", "R"}
in := []string{"A", "B", "C"}
InsertStringSlice(&s, &in, 3) // at the front
fmt.Println(s)
}
|