七、6.字节(byte)与unicode/utf8

1.字节(byte)

package main

import (
    "bytes"
    "fmt"
)
func main() {
    var aa []byte = []byte{'a', 'b', 's'}
    fmt.Printf("%T %#v\n", aa, aa)
    //字节切片转换为 字符串
    s := string(aa)
    fmt.Printf("%T %#v\n", s, s)
    //字符串转换为字节切片
    bs := []byte(s)
    fmt.Printf("%T %#v\n", bs, bs)
    //Compare  比较两个字节切片的大小  后面大于前面返回-1  后面大于前面返回1
    fmt.Println(bytes.Compare([]byte("abc"), []byte("def")))
    //Index 查询索引 如果后面的字符串 在前面的字符串查找不到 那么就返回-1
    //如果可以查找到  那么返回第一个所在的索引
    fmt.Println(bytes.Index([]byte("abcdefabc"), []byte("abc")))
    //Contains   前面的字节切片是否包含后面的的字节切片  返回的是bool
    //前面的包含后面的 返回true  这里是完全包含
    //前面的不包含后面的 返回false
    fmt.Println(bytes.Contains([]byte("abcdefabc"), []byte("oo")))
    bytes02 := []byte{'a', 'b', 'c'}
    bytes03 := []byte{'c', 'b'}
    fmt.Println(bytes.Contains(bytes02, bytes03))
    fmt.Println(bytes.Compare(bytes02, bytes03))
}

2.unicode/utf8

package main

import (
    "fmt"
    "unicode/utf8"
)
func main() {
    s := "我爱中华人名共和国"
    //unicode 字符需要函数来计算长度 len计算的是字节长度
    fmt.Println(len(s))
    fmt.Println(utf8.RuneCountInString(s))
}
发布了95 篇原创文章 · 获赞 12 · 访问量 5773

猜你喜欢

转载自blog.csdn.net/weixin_45413603/article/details/104785571