2020年8月1日 星期六

[ 文章收集 ] Convert between byte array/slice and string

Source From Here
Basics
When you convert between a string and a byte slice (array), you get a brand new slice that contains the same bytes as the string, and vice versa.
The conversion doesn’t change the data;
* the only difference is that strings are immutable, while byte slices can be modified.

If you need to manipulate the characters (runes) of a string, you may want to convert the string to a rune slice instead. See Convert between rune array/slice and string.

Convert string to bytes
When you convert a string to a byte slice, you get a new slice that contains the same bytes as the string:
  1. b := []byte("ABC€")  
  2. fmt.Println(b) // [65 66 67 226 130 172]  
Note that the character € is encoded in UTF-8 using 3 bytes. See the Go rune article for more on UTF-8 encoding of Unicode code points.

Convert bytes to string
When you convert a slice of bytes to a string, you get a new string that contains the same bytes as the slice:
  1. s := string([]byte{656667226130172})  
  2. fmt.Println(s) // ABC€  
Performance
These conversions create a new slice or string, and therefore have time complexity proportional to the number of bytes that are processed.

More efficient alternative
In some cases, you might be able to use a string builder, which can concatenate strings without redundant copying:

Supplement
The Go Blog - Strings, bytes, runes and characters in Go
OpenHome Go - 常用 API - 文字: bytes 套件
OpenHome Go - 常用 API - 文字: strconv、strings 套件

沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...