赵浩翔*_*赵浩翔 19 string unicode go
我是golang的初学者.我想知道如何从字符串中获取unicode字符.
就像,字符串是"你好",我怎么能得到第一个字符"你"?
从其他地方我得到一种方式:
var str = "??"
runes := []rune(str)
fmt.Println(string(runes[0]))
Run Code Online (Sandbox Code Playgroud)
它确实有效.
但是我还有一些问题:
1)还有另一种方法吗?
2)为什么golang不能使用str [0]从字符串中获取unicode字符,
而是获取字节数据?
Did*_*zia 19
首先,您可能需要阅读https://blog.golang.org/strings 它将回答您的部分问题.
Go中的字符串可以包含任意字节.当你写str [i]时,结果是一个字节,索引总是一个字节数.
大多数情况下,字符串以UTF-8编码.您有多种方法可以在字符串中处理UTF-8编码.
例如,您可以使用for ... range语句按符号迭代字符串符文.
var first rune
for _,c := range str {
first = c
break
}
// first now contains the first rune of the string
Run Code Online (Sandbox Code Playgroud)
您还可以使用unicode/utf8包.例如:
r, size := utf8.DecodeRuneInString(str)
// r contains the first rune of the string
// size is the size of the rune in bytes
Run Code Online (Sandbox Code Playgroud)
如果字符串是以UTF-8编码的,则没有直接的方法来访问字符串的第n个符文,因为符文的大小(以字节为单位)不是常量.如果您需要此功能,您可以轻松编写自己的辅助函数(使用for ...范围或使用unicode/utf8包).
| 归档时间: |
|
| 查看次数: |
10519 次 |
| 最近记录: |