12丨字符串

 字符串与字符编码

 

字符串

与其他主要编程语言的差异
1. string 是数据类型,不是引用或指针类型
2. string 是只读的 byte slice,len 函数可以它所包含的 byte 数
3. string 的 byte 数组可以存放任何数据

 

Unicode UTF8

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

 

编码与存储

 

 

 

常用字符串函数

1. strings 包 (https://golang.org/pkg/strings/)
2. strconv 包 (https://golang.org/pkg/strconv/)

测试代码

package ch9

import (
    "testing"
    "unsafe"
)

func TestString(t *testing.T) {
    var s string
    t.Log(s, len(s))
    s = "hello"
    t.Log(len(s))

    //s[1] ='2' //string是不可变的byte slice

    s = "\xE4\xB8\xA5" //可以存储任何二进制数据
    //s = "\xE4\xBA\xBB\xFF"
    t.Log(s)      //
    t.Log(len(s)) // 3  byte数

    s = ""
    t.Log(len(s)) //3    是byte数

    c := []rune(s)                           //     取出字符串里面的Unicode
    t.Log(len(c))                            // 1
    t.Log("rune size:", unsafe.Sizeof(c[0])) // rune size: 4
    t.Logf("中 unicode %x", c[0])             // 中 unicode 4e2d   输出16进制用 x%
    t.Logf("中 UTF8 %x", s)                   //中 UTF8 e4b8ad

}

func TestStringToRune(t *testing.T) {
    s := "中华人民共和国"
    for _, c := range s {
        t.Logf("%[1]c %[1]x ", c) // 都是以第一个对应
    }
   }
/*=== RUN TestStringToRune //遍历输出的是16进制的 Unicode string_test.go:35: 中 4e2d string_test.go:35: 华 534e string_test.go:35: 人 4eba string_test.go:35: 民 6c11 string_test.go:35: 共 5171 string_test.go:35: 和 548c string_test.go:35: 国 56fd --- PASS: TestStringToRune (0.00s) PASS */
t.Logf("%x","中") //e4b8ad UTF8

字符串的转换

package ch9

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, "*")) // A*B*C
}

func TestConv(t *testing.T) {
    s := strconv.Itoa(10)                         //整数到字符串
    t.Log("str" + s)                              //str10
    if i, err := strconv.Atoi("10"); err == nil { // 字符串到整数  反回的是两个值,对错误进行判断
        t.Log(10 + i) //20
    }

}

 

posted @ 2021-01-21 22:30  元贞  阅读(97)  评论(0)    收藏  举报