[go學習筆記]9、go語言中的字符串

字符串

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

輸出git

=== 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個數,不是字符數github

Unicode UTF8

  • Unicode是一種字符集(code point)
  • UTF8是unicode的存儲實現(轉換爲字節序列的規則)

編碼與存儲

字符 「中」
Unicode 0x4E2D
UTF-8 0x4EB8AD
string/[]byte [0xE4,0xB8,0xAD]

經常使用字符串函數

func TestStringToRune(t *testing.T) {
    s := "中華人民共和國"
    for _, c := range s {
        t.Logf("%[1]c %[1]d", c)
    }
}

輸出golang

=== 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

示例代碼請訪問: https://github.com/wenjianzhang/golearningshell

相關文章
相關標籤/搜索