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

aside section._1OhGeD · · 474 次点击 · · 开始浏览    
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

golang学习,切片操作。

/**
将一个切片从start位置开始,删除length个元素
 */
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:]...)... )
}
/**
将切片s1插入到s2的指定位置 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]

有疑问加站长微信联系(非本文作者)

本文来自:简书

感谢作者:aside section._1OhGeD

查看原文:the way to go:练习7.11和练习7.12

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

474 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传