How to convert a string with a null character to a byte buffer in a string in Go?

It:

label := string([]byte{97, 98, 99, 0, 0, 0, 0}) fmt.Printf("%s\n", label) 

does this ( ^@ is a null byte):

 go run test.go abc^@^@^@ 
+6
source share
4 answers

use the strings package.

 package main import ( "fmt" "strings" ) func main() { label := string([]byte{97, 98, 99, 0, 0, 0, 0}) fmt.Println(strings.TrimSpace(label)) } 
+5
source

Note that the first answer will only work with strings that have zero zero after the terminator zero; however, a valid C-style zero-terminated string ends at the first \0 , even if garbage follows it. For example, []byte{97,98,99,0,99,99,0} should be analyzed as abc , not abc^@cc .

To correctly analyze this, use string.Index as shown below to find the first \0 and use it to trim the original byte fragment:

 package main import ( "fmt" "strings" ) func main() { label := []byte{97,98,99,0,99,99,0} s := label[:strings.Index(string(label), "\x00")] fmt.Println(string(s)) } 

EDIT: printed the shortened version as []byte instead of string . Thanks @serbaut for the trick.

+10
source

Here, this function is hidden inside the assembly package S, which finds the first zero byte ([] byte {0}) and returns the length. I assume it is called clen for C-Length.

Sorry that I was late for this answer for a year, but I think it is much easier than the other two (without unnecessary imports, etc.).

 func clen(n []byte) int { for i := 0; i < len(n); i++ { if n[i] == 0 { return i } } return len(n) } 

So,

 label := []byte{97, 98, 99, 0, 0, 0, 0} s := label[:clen(label)] fmt.Println(string(s)) 

What ^ says is to set s to the byte slice in the label from the beginning to the clen(label) index.

The result will be abc with a length of 3.

+6
source

The first answer will not work.

 func TrimSpace(s []byte) []byte { return TrimFunc(s, unicode.IsSpace) } func IsSpace(r rune) bool { // This property isn't the same as Z; special-case it. if uint32(r) <= MaxLatin1 { switch r { case '\t', '\n', '\v', '\f', '\r', ' ', 0x85, 0xA0: return true } return false } return isExcludingLatin(White_Space, r) } 

"\ x00" does not exist in func IsSpace at all.

0
source

Source: https://habr.com/ru/post/925065/


All Articles