Go 学习笔记
字符串
与其他主要编程语言言的差异
- string 是数据类型,不不是引用用或指针类型 s
- tring 是只读的 byte slice,len 函数可以它所包含的 byte 数
- string 的 byte 数组可以存放任何数据
Unicode UTF8
- Unicode 是一一种字符集(code point)
- UTF8 是 unicode 的存储实现 (转换为字节序列列的规则)
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' //string是不可变的byte slice
s = "\xE4\xBA\xBB\xFF"
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 TestStringToRune(t *testing.T){
s := "中华人民共和国"
for _, c := range s{
t.Logf("%[1]c %[1]x", c) //
}
}
编码与存储
字符 “中”
Unicode 0x4E2D
UTF-8 0xE4B8AD
string/[]byte [0xE4,0xB8,0xAD]
常用用字符串串函数
- strings 包 (https://golang.org/pkg/strings/)
- strconv 包 (https://golang.org/pkg/strconv/)
package string_func_test
import (
"testing"
"strconv"
"strings"
)
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 int 转 string
t.Log("str" +s)
if i, err := strconv.Atoi("10"); err == nil { // Atoi string 转 int
t.Log(10 + i)
}
}
atoi 和 itoa 最早出现在c的函数库中,a 表示 ASCII,i 表示integer.