rune相当于是Go的char。

    1. package main
    2. import "fmt"
    3. func main() {
    4. s := "Yes我爱慕课网!"
    5. fmt.Println(len(s)) // 19 len(string) -> 字节数
    6. fmt.Printf("%s\n", []byte(s)) // Yes我爱慕课网!
    7. fmt.Printf("%X\n", []byte(s)) // 596573E68891E788B1E68595E8AFBEE7BD9121
    8. // 对字节进行遍历,共19个字节
    9. for _, b := range []byte(s) {
    10. fmt.Printf("%X ", b) // 59 65 73 E6 88 91 E7 88 B1 E6 85 95 E8 AF BE E7 BD 91 21
    11. // UTF-8编码,Yes和!各占一个字节,每个中文字符占3个字节
    12. }
    13. for i, ch := range s { // ch is a rune(4字节整数)
    14. fmt.Printf("(%d %X) ", i, ch) // (0 59) (1 65) (2 73) (3 6211) (6 7231) (9 6155) (12 8BFE) (15 7F51) ...
    15. // UTF-8编码转换成了Unicode编码,Yes和!各占一个字节,每个中文字符占3个字节
    16. }
    17. fmt.Println(utf8.RuneCountInString(s)) // 9 获得字符数量
    18. bytes := []byte(s)
    19. for len(bytes) > 0 {
    20. ch, size := utf8.DecodeRune(bytes)
    21. bytes = bytes[size:]
    22. fmt.Printf("%c ", ch) // Y e s 我 爱 慕 课 网 !
    23. }
    24. // 如果不想了解字符的底层表示,直接用以下方法遍历字符串即可
    25. for i, ch := range []rune(s) {
    26. fmt.Printf("(%d %c) ", i, ch) // (0 Y) (1 e) (2 s) (3 我) (4 爱) (5 慕) (6 课) (7 网) (8 !)
    27. }
    28. }

    字符串的操作可以到strings包下去寻找相应函数。

    寻找最长不含有重复字符的子串:

    func lengthOfNonRepeatingSubStr(s string) int {
        lastOccurred := make(map[rune]int)
        start := 0
        maxLength := 0
    
        for i, ch := range []rune(s) {
            if lastI, ok := lastOccurred[ch]; ok && lastI >= start {
                start = lastI + 1
            }
            if i-start+1 > maxLength {
                maxLength = i - start + 1
            }
            lastOccurred[ch] = i
        }
    
        return maxLength
    }