我是 go lang 的新手,我想打印字符串数组的单个字节
在下面的代码中,我想一次打印值“h”、“e”、“l”、“l”、“o”,但我无法做到这一点。
func main() {
strslice := make([]string, 4, 5)
strslice[0] = "hello"
strslice[1] = "go"
strslice[2] = "lang"
strslice[3] = "whatsup"
for i := 0; i < len(strslice[i]); i++ {
fmt.Printf("slice is %c \n", strslice[i])
}
}
最佳答案
在 Go 中,字 rune 字作为 UTF-8 编码字节的可变宽度序列存储在字符串中。 ASCII 代码点 (0x00..0x7F) 占用一个字节。其他代码点占用两到四个字节。要单独打印代码点(字符),
package main
import "fmt"
func main() {
strslice := make([]string, 5, 5)
strslice[0] = "hello"
strslice[1] = "go"
strslice[2] = "lang"
strslice[3] = "whatsup"
strslice[4] = "Hello, 世界"
for _, s := range strslice {
for _, c := range s {
fmt.Printf("%c ", c)
}
fmt.Printf("\n")
}
}
输出:
h e l l o
g o
l a n g
w h a t s u p
H e l l o , 世 界
下面是UTF-8编码字节和字符之间区别的说明,
package main
import "fmt"
func main() {
str := "Hello, 世界"
fmt.Println("Bytes:")
for i := 0; i < len(str); i++ {
fmt.Printf("'%c' ", str[i])
}
fmt.Printf("\n")
fmt.Println("Characters:")
for _, c := range str {
fmt.Printf("'%c' ", c)
}
fmt.Printf("\n")
}
输出:
Bytes:
'H' 'e' 'l' 'l' 'o' ',' ' ' 'ä' '¸' '' 'ç' '' ''
Characters:
'H' 'e' 'l' 'l' 'o' ',' ' ' '世' '界'
引用资料:
关于go - 在 golang 的字符串数组中打印特定字节的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22835209/