dongshi1207
2018-06-15 15:15
浏览 730
已采纳

Golang中的字符串转换和Unicode

I am reading Go Essentials:

String in Go is an immutable sequence of bytes (8-bit byte values) This is different than languages like Python, C#, Java or Swift where strings are Unicode.

I am playing around with following code:

s := "日本語"
b :=[]byte{0xe6, 0x97, 0xa5, 0xe6, 0x9c, 0xac, 0xe8, 0xaa, 0x9e}
fmt.Println(string(b) == s) // true

for i, runeChar := range b {
    fmt.Printf("byte position %d: %#U
", i, runeChar)
}

//byte position 0: U+00E6 'æ'
//byte position 1: U+0097
//byte position 2: U+00A5 '¥'
//byte position 3: U+00E6 'æ'
//byte position 4: U+009C
//byte position 5: U+00AC '¬'
//byte position 6: U+00E8 'è'
//byte position 7: U+00AA 'ª'
//byte position 8: U+009E

for i, runeChar := range string(b) {
    fmt.Printf("byte position %d: %#U
", i, runeChar)
}

//byte position 0: U+65E5 '日'
//byte position 3: U+672C '本'
//byte position 6: U+8A9E '語'

Questions:

  1. From where does Golang get Unicode for encoding byte array when custing to string? How does rune form? Does Golang compilator get Unicode from text file encoding during compilation?

  2. What are advantages and disadvantages of implementing String like a byte array, instead of utf-16 chars array like in Java?

图片转代码服务由CSDN问答提供 功能建议

我正在阅读 Go必备知识

Go中的字符串是字节的不可变序列(8位字节值) 这与Python,C#,Java或Swift这样的语言(其中 字符串为Unicode)不同。

我正在玩以下代码:

  s:=“日本语” 
b:= [] byte {0xe6,0x97,0xa5,0xe6,0x9c,0xac,0xe8,0xaa,0x9e} 
fmt.Println(string  (b)== s)// true 
 
对于i,runeChar:=范围b {
 fmt.Printf(“字节位置%d:%#U 
”,i,runeChar)
} 
  
 //字节位置0:U + 00E6'æ'
 //字节位置1:U + 0097 
 //字节位置2:U + 00A5'¥'
 //字节位置3:U + 00E6  'æ'
 //字节位置4:U + 009C 
 //字节位置5:U + 00AC'¬'
 //字节位置6:U + 00E8'è'
 //字节位置7:  U + 00AA'ª'
 //字节位置8:U + 009E 
 
(对于i,runeChar:=范围字符串(b){
 fmt.Printf(“ byte pos 位置%d:%#U 
“,i,runeChar)
} 
 
 //字节位置0:U + 65E5'日'
 //字节位置3:U + 672C'本'
  //字节位置6:U + 8A9E'lang'
   
 
 

问题:

    \ n
  1. 当捕获字符串时,Golang从何处获取用于编码字节数组的Unicode? rune 如何形成? Golang编译器在编译期间是否从文本文件编码中获取Unicode?

  2. 以字节数组而不是Java中的utf-16 chars数组形式实现String的优点和缺点是什么?

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

相关推荐 更多相似问题