字符串
- string是数据类型,不是引用或指针类型
- string是只读的byte slice,len函数可以返回字符串包含的byte数量
- string的byte数组可以存放任何数据
Unicode UTF8
- Unicode 是一种字符集(code point)
- 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)
}
}
常用字符串函数
- strings包
- 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
网友评论