GO_String字符串_06

字符串

  1. string 是数据类型,不是引用或指针类型
  2. string 是只读的 byte slice, len 函数可以它所包含的 byte 数
  3. string 的 byte 数组可以存放任何数据

Unicode UTF8

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

编码与存储

在这里插入图片描述

Demo1

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" //可以存储任何二进制数据
	s = "\xE4\xBA\xBB\xFF"
	t.Log(s)
	t.Log(len(s))
	s = "中"
	t.Log(len(s)) //是byte数

	c := []rune(s)
	t.Log(len(c))
	//	t.Log("rune size:", unsafe.Sizeof(c[0]))
	t.Logf("中 unicode %x", c[0])
	t.Logf("中 UTF8 %x", s)
}

result:

=== RUN   TestString
    string_test.go:7: 
    string_test.go:9: 5
    string_test.go:13: 亻�
    string_test.go:14: 4
    string_test.go:16: 3
    string_test.go:19: 1
    string_test.go:21: 中 unicode 4e2d
    string_test.go:22: 中 UTF8 e4b8ad
--- PASS: TestString (0.00s)

Demo2

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

result:

=== RUN   TestStringToRune
    string_test.go:28: 中 4e2d
    string_test.go:28: 华 534e
    string_test.go:28: 人 4eba
    string_test.go:28: 民 6c11
    string_test.go:28:5171
    string_test.go:28: 和 548c
    string_test.go:28: 国 56fd
--- PASS: TestStringToRune (0.00s)

Demo3

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

result:

=== RUN   TestStringFn
    string_fun_test.go:13: A
    string_fun_test.go:13: B
    string_fun_test.go:13: C
    string_fun_test.go:15: A-B-C
--- PASS: TestStringFn (0.00s)
PASS

Demo4

func TestConv(t *testing.T) {
    
    
	s := strconv.Itoa(10)// 整型转string
	t.Log("str" + s)
	// string转整型
	if i, err := strconv.Atoi("10"); err == nil {
    
    
		t.Log(10 + i)
	}
}

result:

=== RUN   TestConv
    string_fun_test.go:20: str10
    string_fun_test.go:22: 20
--- PASS: TestConv (0.00s)
PASS

PS:学习笔记,侵删!

猜你喜欢

转载自blog.csdn.net/qq_31686241/article/details/126612843