How can I remove a byte of type []byte

huangapple go评论90阅读模式
英文:

How can I remove a byte of type []byte

问题

我有一个变量cmd,返回的是[50 48 ... 50 53 10]

有可能删除这个变量的任何字节吗?在我的情况下,我想删除最后一个字节[10] == LF(换行符),以获得:[50 48 ... 50 53]

附注:我没有找到任何类似的问题,因为函数bytes.Trim(cmd, "\x10")对我不起作用,或者说,我没有正确使用它...

英文:

I have a variable cmd that returns [50 48 ... 50 53 10]

It's possible to remove any bytes of this var? In my case, I want to remove the last byte [10] == LF (Line Feed) to obtain: [50 48 ... 50 53]

P.S.: I have not found any similar question because the function bytes.Trim(cmd, "\x10") does not work for me, or maybe, I don't use it fine...

答案1

得分: 4

例如,

package main

import (
    "bytes"
    "fmt"
)

func main() {
    b := []byte{50, 48, 50, 53, 10}
    fmt.Println(b)
    b = bytes.TrimSuffix(b, []byte{10}) // 换行符
    fmt.Println(b)

    b = []byte{50, 48, 50, 53, 10}
    fmt.Println(b)
    b = bytes.TrimSuffix(b, []byte("\n")) // 换行符
    fmt.Println(b)
}

输出:

[50 48 50 53 10]
[50 48 50 53]
[50 48 50 53 10]
[50 48 50 53]
英文:

For example,

package main

import (
	"bytes"
	"fmt"
)

func main() {
	b := []byte{50, 48, 50, 53, 10}
	fmt.Println(b)
	b = bytes.TrimSuffix(b, []byte{10}) // Line Feed
	fmt.Println(b)

	b = []byte{50, 48, 50, 53, 10}
	fmt.Println(b)
	b = bytes.TrimSuffix(b, []byte("\n")) // Line Feed
	fmt.Println(b)
}

Output:

[50 48 50 53 10]
[50 48 50 53]
[50 48 50 53 10]
[50 48 50 53]

答案2

得分: 3

没有内置的方法来完成这个任务,但你仍然可以像这样做:

cmd := []int{1, 2, 3, 3, 5, 6, 7, 8}
expected := cmd[:len(cmd)-1]

这段代码可以将 cmd 切片中的最后一个元素去掉,并将结果赋值给 expected

英文:

There is no such built-in method to do this, but you can still do it like this:

cmd := []int{1, 2, 3, 3, 5, 6, 7, 8}
expected := cmd[:len(cmd)-1])

huangapple
  • 本文由 发表于 2017年6月7日 17:42:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/44409010.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定