Go语言学习笔记-字符串

2019-04-12  本文已影响0人  noonenote

字符串

  1. string是数据类型,不是引用或指针类型
  2. string是只读的byte slice,len函数可以返回字符串包含的byte数量
  3. string的byte数组可以存放任何数据

Unicode UTF8

  1. Unicode 是一种字符集(code point)
  2. UTF8是unicode的存储实现(转换为字节序列的规则)

编码与存储

字符 "中"
unicode 0x4E2D
UTF8 0xE4B8AD
string/[]byte [0xE4,0xB8,0xAD]


package string_test
import "testing"

func TestString(t *testing.T) {
        var s string
        t.Log(s)
        s = "hello"
        t.Log(len(s))
        //s[1] = '3'//cannot assign to s[1]
        t.Log(s)
        s = "\xE4\xB8\xA5"
        t.Log(s)
        t.Log(len(s))
        s = "中"
        t.Log(len(s))
        c := []rune(s)
        t.Log(len(c))
        t.Logf("中 unicode %x", c[0])
        t.Logf("中 UTF8 %x", s)
}

func TestStrongToRune(t *testing.T) {
        s := "中华人民共和国"
        for _, c := range s {
                t.Logf("%[1]c %[1]x",c)

        }

}

常用字符串函数

  1. strings包
  2. strconv包

package string_fun
import "testing"
import "strings"
import "strconv"

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)
        t.Log("str"+ s)
        if i,err := strconv.Atoi("10");err==nil {
                t.Log(10 + i)
        }
}

itoa: Integer TO Alphabet
atoi: Alphabet TO Integer

上一篇 下一篇

猜你喜欢

热点阅读