Files

43 lines
960 B
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package main
import (
"fmt"
"unicode/utf8"
)
func main() {
str := "Go 学习 🚀"
fmt.Println("===== 1. 字符串长度(字节数) =====")
fmt.Println("len(str) =", len(str)) // 字节长度
fmt.Println("\n===== 2. 字符个数(rune 数) =====")
fmt.Println("字符数 =", utf8.RuneCountInString(str))
fmt.Println("\n===== 3. 正确遍历(for range =====")
for idx, r := range str {
fmt.Printf("索引:%d, 字符:%c\n", idx, r)
}
fmt.Println("\n===== 4. 转 []rune =====")
runes := []rune(str)
fmt.Printf("rune 切片长度:%d\n", len(runes))
for i, r := range runes {
fmt.Printf("第%d个字符:%c\n", i, r)
}
fmt.Println("\n✅ Unicode / UTF-8 / rune 演示完成!")
var r rune = '学'
fmt.Printf("rune(%c) = %d\n", r, r)
s := "Go学习"
for i := 0; i < len(s); i++ {
fmt.Printf("%c ", s[i]) // 中文乱码!
}
s2 := "Go学习"
for _, r := range s2 {
fmt.Printf("%c ", r) // G o 学 习 ✅
}
}