Golang字符串遍历
Last updated
Last updated
package main
import (
"fmt"
"reflect"
)
func main() {
str := "Hello,世界"
//utf-8遍历
for i := 0; i < len(str); i++ {
ch := str[i]
ctype:=reflect.TypeOf(ch)
fmt.Printf("%s ",ctype) //uint8
}
fmt.Println("=============>Unicode遍历")
//Unicode遍历
for _, ch1 := range str {
ctype:=reflect.TypeOf(ch1)
fmt.Printf("%s ",ctype) //int32
}
}修改字符串中的字节(用 []byte):
func main() {
s := "Hello 世界!"
b := []byte(s) // 转换为 []byte,自动复制数据
b[5] = ',' // 修改 []byte
fmt.Printf("%s\n", s) // s 不能被修改,内容保持不变
fmt.Printf("%s\n", b) // 修改后的数据
}
修改字符串中的字符(用 []rune):
func main() {
s := "Hello 世界!"
r := []rune(s) // 转换为 []rune,自动复制数据
r[6] = '中' // 修改 []rune
r[7] = '国' // 修改 []rune
fmt.Println(s) // s 不能被修改,内容保持不变
fmt.Println(string(r)) // 转换为字符串,又一次复制数据
}