Skip to content

Latest commit

 

History

History
66 lines (34 loc) · 1.71 KB

4.3-字符串、数组和切片的应用.md

File metadata and controls

66 lines (34 loc) · 1.71 KB

#18、 字符串、数组和切片的应用

1、从字符串生成字节切片

    str := []byte() //字符串底层是字符数组
    str := []rune() //生成字符切片,rune类型可以统计其他编码字符

2、截取字符串,获取子串

    substr := str[start:end] //获取从索引start到end-1位置的字符串
    str[start:] //获取从start到len(str)-1的子串
    str[:end] // 获取从0到len(str)-1的子串

3、字符串内存结构

 字符串:双字结构,一个指向字符串的指针和字符串长度,值类型

4、修改字符串中的某个字符

 必须先转换成 []byte或[]rune数组,使用字符数组修改,再转成string
 
 strByte := []byte(str)
 strByte[1] =  'x'
 str = string(strByte)   

5、搜索和排序切片

 搜索:必须先排序,标准库中使用二分法查找
 排序:使用sort包中的函数进行排序     

6、append常用操作

  • a. 追加元素

       append(s,ele)
    
  • b. 复制a切片到新切片b

      b = make([]T,len(a))
      copy(b,a)
    
  • c. 删除位于索引 i 的元素

     append(s[:i],s[i+1:]...)                     
    
  • d. 切除切片 a 中从索引 i 至 j 位置的元素

     append(a[:i],a[j]...)
    
  • e. 为切片 a 扩展 j 个元素长度

    append(a,make([]T,j)...)     
    
  • f. 在索引 i 的位置插入元素 x

    append(s[:i],append([]T{x},s[i:]...))
    
  • g. 在索引 i 的位置插入长度为 j 的新切片

    append(s[:i],append(make([]T,j),s[i:]...)...)