The type rune is a synonym int32. byte is a synonym uint8. We can create [] rune (or [] int32) for a unicode string. For a string which only has ASCII characters, we can create [] byte, [] uint8 or [] rune. To convert this array back to string, use string(array value). See the below example.
package main
import (
"fmt"
)
func main() {
var s, t string
var r, k []rune
s = "世界和平"
//create an array of rune. Also can do r =[]int32(s)
r = []rune(s)
//change back to string
t = string(r)
fmt.Println(t)
k = []rune{19990, 30028, 21644, 24179}
fmt.Println(string(k))
}
convert string to array; Then convert back for string which has only ASCII characters
package main
import (
"fmt"
)
func main() {
var s, t string
var r []uint8
s = "hello world"
r = []uint8(s)
//change back to string
t = string(r)
fmt.Println(t)
}
No comments:
Post a Comment