本文大纲
本文继续学习GO语言基础知识点。

1、字符串String
String
是Go语言的基本类型,在初始化后不能修改,Go字符串是一串固定长度的字符连接起来的字符序列,当然它也是一个字节的切片(Slice)。
- import ("fmt")
- func main() {
- name := "Hello World" //声明一个值为 Hello World的字符串变量 name
- fmt.Println(name)
- }
String常用操作:获取长度和遍历
1、获取字符串长度:len()函数
- str1 := "hello world"
- fmt.Println(len(str1)) // 11
2、字符串遍历方式1:
- str := "hello"
- for i := 0; i < len(str); i++ {
- fmt.Println(i,str[i])
- }
3、字符串遍历方式2:
- str := "hello"
- for i,ch := range str {
- fmt.Println(i,ch)
- }
4、使用函数string()将其他类型转换为字符串
- num := 12
- fmt.Printf("%T \n", string(num) // "12" string
5、字符串拼接
- str1 := "hello "
- str2 := " world"
- //创建字节缓冲
- var stringBuilder strings.Builder
- //把字符串写入缓冲
- stringBuilder.WriteString(str1)
- stringBuilder.WriteString(str2)
- //将缓冲以字符串形式输出
- fmt.Println(stringBuilder.String())
字符串的strings包
- //查找s在字符串str中的索引
- Index(str, s string) int
- //判断str是否包含s
- Contains(str, s string) bool
- //通过字符串str连接切片 s
- Join(s []string, str string) string
- //替换字符串str中old字符串为new字符串,n表示替换的次数,小于0全部替换
- Replace(str,old,new string,n int) string
字符串的strconv包:
用于与基本类型之间的转换,常用函数有Append、Format、Parse
- Append 系列函数将整数等转换为字符串后,添加到现有的字节数组中
- Format 系列函数把其他类型的转换为字符串
- Parse 系列函数把字符串转换为其他类型
2、切片Slice
切片(slice)的作用是解决GO数组长度不能扩展的问题。是一种方便、灵活且强大的包装器。它本身没有任何数据,只是对现有数组的引用。
切片定义
切片不需要说明长度, 或使用make()函数来创建切片:
- var slice1 []type = make([]type, len)
- 也可以简写为
- slice1 := make([]type, len)
示例
- func main() {
- /* 创建切片 */
- numbers := []int{0,1,2,3,4,5,6,7,8}
- printSlice(numbers)
- /* 打印原始切片 */
- fmt.Println("numbers ==", numbers)
- /* 打印子切片从索引1(包含) 到索引4(不包含)*/
- fmt.Println("numbers[1:4] ==", numbers[1:4])
- /* 默认下限为 0*/
- fmt.Println("numbers[:3] ==", numbers[:3])
- }
- func printSlice(x []int){
- fmt.Printf("len=%d cap=%d slice=%v\n",len(x),cap(x),x)
- }
- 打印结果:
- len=9 cap=9 slice=[0 1 2 3 4 5 6 7 8]
- numbers == [0 1 2 3 4 5 6 7 8]
- numbers[1:4] == [1 2 3]
- numbers[:3] == [0 1 2]
3、集合Map
Map是Go语言的内置类型,将一个值与一个键关联起来,是一种无序的键值对的集合,可以使用相应的键检索值(类比Java中的Map来记)。
- // 声明一个map类型,[]内的类型指任意可以进行比较的类型 int指值类型
- m := map[string]int{"a":1,"b":2}
- fmt.Print(m["a"])
示例:
- func main() {
- var countryCapitalMap map[string]string
- /* 创建集合 */
- countryCapitalMap = make(map[string]string)
- /* map 插入 key-value 对,各个国家对应的首都 */
- countryCapitalMap["France"] = "Paris"
- countryCapitalMap["Italy"] = "Rome"
- countryCapitalMap["Japan"] = "Tokyo"
- countryCapitalMap["India"] = "New Delhi"
- /* 使用 key 输出 map 值 */
- for country := range countryCapitalMap {
- fmt.Println("Capital of",country,"is",countryCapitalMap[country])
- }
运行结果:
Capital of France is Paris
Capital of Italy is Rome
Capital of Japan is Tokyo
Capital of India is New Delhi
以上就是GO语言基本类型String和Slice,Map操作详解的详细内容,更多关于GO基本类型String Slice Map的资料请关注w3xue其它相关文章!