Go语言基础05 _string

Go语言基础05 _string

1、基本使用
package string

import "testing"

func TestString(t *testing.T) {
   var s string
   t.Log(s)
   s = "Hello"
   t.Log(len(s))
   t.Log(s[1]) // 输出码值 (byte)
   //s[1] = '3' // string 是不可变的 byte slice
   s = "\xE4\xB8\xA5"
   t.Log(s) // 严
   t.Log(len(s))
   s = "中"
   t.Log(len(s)) // 输出 string 的 byte 数

   c := []rune(s) // 转化为 Unicode 码
   t.Log("len(c) = ", len(c))
   t.Logf("中 Unicode %x", c[0])
   t.Logf("中 UTF8 %x", s)
}

func TestStringToRune(t *testing.T) {
   s := "中华人民共和国"
   for _, c := range s {
      t.Logf("%[1]c %[1]x", c)
   }
}
2、一些函数
package string

import (
   "strconv"
   "strings"
   "testing"
)

func TestStringFn(t *testing.T) {
   s := "A,B,C"
   parts := strings.Split(s, ",")
   for _, part := range parts {
      t.Log(part)
   }
   t.Log(strings.Join(parts, "-"))
}

func TestConv(t *testing.T) {
   s := strconv.Itoa(10) // 数字到字符 Itoa
   t.Log("str" + s)
   if i,err := strconv.Atoi("10");err == nil{ // 字符到数字 Atoi (需要手动判断接收)
      t.Log(10 + i)
   }

   if i,err := strconv.Atoi("1998");err == nil{ // 字符到数字 Atoi (需要手动判断接收 ,无法对非数值字符串 进行 此操作)
      t.Log(10 + i)
   }

}

只介绍到了部分常用的函数,如果需要请自行了解

posted on 2021-09-13 17:12  OwlInTheOaktree  阅读(22)  评论(0编辑  收藏  举报