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

查看:993
本文介绍了如何在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字符。字符串的行为像字节。 rune是标识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 Programming Language Specification 部分。转换

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

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