# the way to go:练习7.11和练习7.12

aside section._1OhGeD · · 438 次点击 · · 开始浏览

golang学习，切片操作。

``````/**

*/
func removeStringSlice(slice []string, start, length int) []string {
if ( start + length ) > len(slice) {
panic("越界")
}
return append( slice[:start], slice[start+length:]... )
}
``````
``````将切片s1插入到s2的指定位置 index处
func insertIntSlice(s1, slice []int, index int) []int {
return append( slice[:index] , append(s1,slice[index:]...)... )
}
``````
``````/**

*/
func insertStringSlice(s1, s2 []int, index int) []int {
if index > len(s2){
panic("位置不存在")
}

//将目标切片按照指定位置分为两个临时切片
tmp1 := s2[:index]
tmp2 := s2[index:]

//创建一个长度为s1+s2的切片用于存储两个切片的值
newTmp := make([]int, len(s2)+len(s1))

//重组切片
copy(newTmp, tmp1)
copy(newTmp[index:len(s1)+index], s1)
copy(newTmp[len(newTmp)-len(tmp2):], tmp2)
return newTmp
}
``````
``````func main(){
slice := []string{"a","b","c","d","e","f","g"}
resRemoveString := removeStringSlice(slice,1,4)
fmt.Println(resRemoveString)

s2 := []int{1,2,3,4,5}
s1 := []int{33,22,11}
resInsert := insertIntSlice(s1,s2,4)
fmt.Println(resInsert)

ss1 := []int{1,2,3,4,5}
ss2 := []int{10,20,30,40,50}
index := 2
ss2 = insertStringSlice(ss1, ss2, index)
fmt.Println(ss2)
}
``````

``````[a f g]
[1 2 3 4 33 22 11 5]
[10 20 1 2 3 4 5 30 40 50]
``````

0 回复

• 请尽量让自己的回复能够对别人有帮助
• 支持 Markdown 格式, **粗体**、~~删除线~~、``单行代码``
• 支持 @ 本站用户；支持表情（输入 : 提示），见 Emoji cheat sheet
• 图片支持拖拽、截图粘贴等方式上传

golang学习，切片操作。

``````/**

*/
func removeStringSlice(slice []string, start, length int) []string {
if ( start + length ) > len(slice) {
panic("越界")
}
return append( slice[:start], slice[start+length:]... )
}
``````
``````将切片s1插入到s2的指定位置 index处
func insertIntSlice(s1, slice []int, index int) []int {
return append( slice[:index] , append(s1,slice[index:]...)... )
}
``````
``````/**

*/
func insertStringSlice(s1, s2 []int, index int) []int {
if index > len(s2){
panic("位置不存在")
}

//将目标切片按照指定位置分为两个临时切片
tmp1 := s2[:index]
tmp2 := s2[index:]

//创建一个长度为s1+s2的切片用于存储两个切片的值
newTmp := make([]int, len(s2)+len(s1))

//重组切片
copy(newTmp, tmp1)
copy(newTmp[index:len(s1)+index], s1)
copy(newTmp[len(newTmp)-len(tmp2):], tmp2)
return newTmp
}
``````
``````func main(){
slice := []string{"a","b","c","d","e","f","g"}
resRemoveString := removeStringSlice(slice,1,4)
fmt.Println(resRemoveString)

s2 := []int{1,2,3,4,5}
s1 := []int{33,22,11}
resInsert := insertIntSlice(s1,s2,4)
fmt.Println(resInsert)

ss1 := []int{1,2,3,4,5}
ss2 := []int{10,20,30,40,50}
index := 2
ss2 = insertStringSlice(ss1, ss2, index)
fmt.Println(ss2)
}
``````

``````[a f g]
[1 2 3 4 33 22 11 5]
[10 20 1 2 3 4 5 30 40 50]
``````