如何索引 Golang 字符串中的字符? [英] How to index characters in a Golang string?

查看:41
本文介绍了如何索引 Golang 字符串中的字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何获得E"输出而不是 69?

How to get an "E" output rather than 69?

package main

import "fmt"

func main() {
    fmt.Print("HELLO"[1])
}

Golang 有字符转字节的功能吗?

Does Golang have function to convert a char to byte and vice versa?

推荐答案

解释的字符串文字是双引号 "" 之间的字符序列,使用(可能是多字节)UTF-8 编码单个字符.在 UTF-8 中,ASCII 字符是对应于前 128 个 Unicode 字符的单字节.字符串的行为类似于字节片.符文是标识 Unicode 代码点的整数值.因此,

Interpreted string literals are character sequences between double quotes "" using the (possibly multi-byte) UTF-8 encoding of individual characters. In UTF-8, ASCII characters are single-byte corresponding to the first 128 Unicode characters. Strings behave like slices of bytes. A rune is an integer value identifying a Unicode code point. Therefore,

package main

import "fmt"

func main() {
    fmt.Println(string("Hello"[1]))              // ASCII only
    fmt.Println(string([]rune("Hello, 世界")[1])) // UTF-8
    fmt.Println(string([]rune("Hello, 世界")[8])) // UTF-8
}

输出:

e
e
界

<小时>

阅读:

Go 编程语言规范 部分关于 转化次数.

Go 博客:Go 中的字符串、字节、符文和字符

这篇关于如何索引 Golang 字符串中的字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆