Go lang等效于JavaScript的charCode()方法 [英] Go lang's equivalent of charCode() method of JavaScript
问题描述
JavaScript中的charCodeAt()
方法返回给定索引处字符的数字Unicode值,例如
The charCodeAt()
method in JavaScript returns the numeric Unicode value of the character at the given index, e.g.
"s".charCodeAt(0) // returns 115
我该如何获取Go中相同字符串/字母的数字unicode值?
How would I go by to get the numeric unicode value of the the same string/letter in Go?
推荐答案
Go中的字符类型为rune
,这是int32
的别名,因此它已经是一个数字,只需打印即可.
The character type in Go is rune
which is an alias for int32
so it is already a number, just print it.
您仍然需要一种方法来使角色位于指定位置.最简单的方法是将string
转换为可以索引的[]rune
.要将string
转换为符文,只需使用类型转换[]rune("some string")
:
You still need a way to get the character at the specified position. Simplest way is to convert the string
to a []rune
which you can index. To convert a string
to runes, simply use the type conversion []rune("some string")
:
fmt.Println([]rune("s")[0])
打印:
115
如果希望将其打印为字符,请使用%c
格式字符串:
If you want it printed as a character, use the %c
format string:
fmt.Println([]rune("absdef")[2]) // Also prints 115
fmt.Printf("%c", []rune("absdef")[2]) // Prints s
还请注意,string
上的for range
遍历字符串的符文,因此您也可以使用它.它比将整个string
转换为[]rune
更为有效:
Also note that the for range
on a string
iterates over the runes of the string, so you can also use that. It is more efficient than converting the whole string
to []rune
:
i := 0
for _, r := range "absdef" {
if i == 2 {
fmt.Println(r)
break
}
i++
}
请注意,计数器i
必须是一个不同的计数器,它不能是循环迭代变量,因为for range
返回的是字节位置,而不是rune
索引(如果string
包含UTF-8表示形式的多字节字符.
Note that the counter i
must be a distinct counter, it cannot be the loop iteration variable, as the for range
returns the byte position and not the rune
index (which will be different if the string
contains multi-byte characters in the UTF-8 representation).
将其包装为函数:
func charCodeAt(s string, n int) rune {
i := 0
for _, r := range s {
if i == n {
return r
}
i++
}
return 0
}
在去游乐场上尝试一下.
还请注意,Go中的string
作为[]byte
存储在内存中,这是文本的UTF-8编码字节序列(请阅读博客文章是's'
的字节值,即115
.
Also note that string
s in Go are stored in memory as a []byte
which is the UTF-8 encoded byte sequence of the text (read the blog post Strings, bytes, runes and characters in Go for more info). If you have guarantees that the string
uses characters whose code is less than 127, you can simply work with bytes. That is indexing a string
in Go indexes its bytes, so for example "s"[0]
is the byte value of 's'
which is 115
.
fmt.Println("s"[0]) // Prints 115
fmt.Println("absdef"[2]) // Prints 115
这篇关于Go lang等效于JavaScript的charCode()方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!