查看字符串
方式1
const nihongo = "日本語"
for index, runeValue := range nihongo {
fmt.Printf("%#U starts at byte position %d\n", runeValue, index)
}
方式2
const nihongo = "日本語"
for i, w := 0, 0; i < len(nihongo); i += w {
runeValue, width := utf8.DecodeRuneInString(nihongo[i:])
fmt.Printf("%#U starts at byte position %d\n", runeValue, i)
fmt.Printf("%c starts at byte position %d\n", runeValue, i)
w = width
}
Golang 文本长度
package main
import (
"fmt"
"unicode/utf8"
)
func main() {
buf := []byte("Hello, 世界")
fmt.Println("bytes =", len(buf))
fmt.Println("runes =", utf8.RuneCount(buf))
}
子字符串
s := "我就这是good,给力666"
sizesplit := 0
re := ""
for _, runeValue := range s {
if sizesplit <= 3 {
continue
}
if sizesplit >= 20 {
break
}
re += fmt.Sprintf("%c", runeValue)
}
fmt.Println(re)
引用
https://blog.golang.org/strings
https://golang.org/pkg/unicode/utf8/#RuneCount