英文:
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])
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论