欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

[go学习笔记]九、go语言中的字符串

程序员文章站 2022-06-19 10:21:18
字符串 string是数据类型,不是引用或者指针类型 string是只读的byte slice,len函数可以获取他所有的byte数量 string的byte数组可以存放任何数据 输出 注意:len获取的string的byte个数,不是字符数 Unicode UTF8 Unicode是一种字符集(c ......

字符串

  • string是数据类型,不是引用或者指针类型
  • string是只读的byte slice,len函数可以获取他所有的byte数量
  • string的byte数组可以存放任何数据
func teststring(t *testing.t) {
    var s string
    t.log(s) //初始化为默认零值""
    s = "hello"
    t.log(len(s))
    //s[1] = '3' //string是不可变的byte slice
    s = "\xe4\xb8\xa5"
    t.log(s)
    t.log(len(s))
    //s = "中"
    //t.log(len(s))
    //c := []rune(s)
    //t.log("rune size:", unsafe.sizeof(c[0]))
    //t.logf("中 unicode %x", c[0])
    //t.logf("中 utf8 %x", s)
}

输出

=== run   teststring
--- pass: teststring (0.00s)
    string_test.go:9: 
    string_test.go:11: 5
    string_test.go:14: 严
    string_test.go:15: 3
pass

process finished with exit code 0

注意:len获取的string的byte个数,不是字符数

unicode utf8

  • unicode是一种字符集(code point)
  • utf8是unicode的存储实现(转换为字节序列的规则)

编码与存储

字符 “中”
unicode 0x4e2d
utf-8 0x4eb8ad
string/[]byte [0xe4,0xb8,0xad]

常用字符串函数

  • string包()
  • strconv包()
func teststringtorune(t *testing.t) {
    s := "*"
    for _, c := range s {
        t.logf("%[1]c %[1]d", c)
    }
}

输出

=== run   teststringtorune
--- pass: teststringtorune (0.00s)
    string_test.go:28: 中 20013
    string_test.go:28: 华 21326
    string_test.go:28: 人 20154
    string_test.go:28: 民 27665
    string_test.go:28: 共 20849
    string_test.go:28: 和 21644
    string_test.go:28: 国 22269
pass

process finished with exit code 0

转换

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)
    }

}
=== run   testconv
--- pass: testconv (0.00s)
    string_fun_test.go:20: str:10
    string_fun_test.go:22: 20
pass

process finished with exit code 0

示例代码请访问: