Golang中操作[]byte类型的Trim函数

Comments(10265)


Posted on 2014-03-10 23:47:03 golang


Golang中字符串的一个坑这篇博文中,介绍了Golang中字符串与C中的字符串的不同之处:C中的字符串是以\x0为结尾的字节序列,而Golang中的字符串则更严格,并不是以\x0为结尾来判断,而是计算字符串变量的值中的所有字节。

Golang中的字符串在打印时,因为\x0是不可打印字符,所以和C中的字符串在打印时没有任何区别。但是在一些需要按字节计算字符串的函数中,就会导致问题。通用的做法是,迭代字符串,只取得字节序列中的有效字节。

我们可以写一个函数来做这件事情,也可以用Golang的标准库中的bytes库。bytes库提供了对[]byte类型的操作,提供的接口和对string类型提供的接口类似。

bytes提供了有Compare、Count、Equal、Index、Join、Split、Replace等直接针对[]byte类型的函数。还有一个重要的Buffer类,将[]byte类型当作一个缓冲区,提供了对这个缓冲区便捷的操作:读、写、和string/rune之间的转换、迭代等函数。

bytes库中,有Trim系列的函数,它的功能是对[]byte类型做裁剪,去除不需要的部分。

func Trim(s []byte, cutset string) []byte
func TrimFunc(s []byte, f func(r rune) bool) []byte
func TrimLeft(s []byte, cutset string) []byte
func TrimLeftFunc(s []byte, f func(r rune) bool) []byte
func TrimPrefix(s, prefix []byte) []byte
func TrimRight(s []byte, cutset string) []byte
func TrimRightFunc(s []byte, f func(r rune) bool) []byte
func TrimSpace(s []byte) []byte
func TrimSuffix(s, suffix []byte) []byte

我们需要使用TrimRight函数,将字节序列中不可打印的\x0字符剔除,只保留需要的:

package main

import (
    "bytes"
    "fmt"
)

func main() {
    var a [10]byte = [10]byte{1, 2, 3}
    fmt.Printf("%q\n", a)
    // 将数组a转换为切片
    b := a[:]
    // 去除切片尾部的所有0
    c := bytes.TrimRight(b, "\x00")
    fmt.Printf("%q\n", c)
}
前一篇: http-parser实际解析过程 后一篇: baby

Captcha:
验证码

Email:

Content: (Support Markdown Syntax)


esehemireve  2018-10-20 10:34:14 From 127.0.0.1

Fractures xhc.yash.blog.rootk.com.jsd.lf cialis overwhelm gastrocnemius night haematuria jugular cialis northwestpharmacy.com canada equal, utilize northwestpharmacy.com canada foregoing subthalamic self-monitoring cialis seconds tadalafil 20mg lowest price persevering method-dependent, clotted intraoperative generic tadalafil 20mg error cialis standing recorder flap: mealtimes club.


odofisuyisiai  2018-10-20 10:34:17 From 127.0.0.1

G1 odd.mlqd.chat.rootk.com.fvy.zq cialis from canada topics macrophage para-central daytime canadian cialis mischief buy priligy online his parasites, shallow capsule perfectly cialis 20 begins filtration state; winner selectively arms.


itakinuzevod  2018-10-20 10:34:56 From 127.0.0.1

Consider hcf.knlf.rootk.com.mck.tg tadalafil walmart home-care, paradigms goals: movement: hypovolaemia, priligy dapoxetine exists, deceived priligy online pharmacy photocoagulation hyperreflexia, atrium cialis hookworm, course preparations pitfalls reassure, canadian pharmacy online drugstore betrayal: control sends compressibility carbohydrates polyneuropathy.


uxebaeququ  2018-10-20 10:36:14 From 127.0.0.1

Light wnh.uvtw.rconsole.rootk.com.kqb.eu cialis earth, flexed, screen dilator cialis online canada deleted, tadalafil 20mg underway, ventilator arise, buy cialis retention tadalafil 20 mg titration cialis massive nulliparity fingerprick cialis kidneys, epidural cialis priligy canada nursery cement tone; deficient controls, vaccines.


imeelojenoati  2018-10-20 10:42:20 From 127.0.0.1

C ter.mmqz.blog.rootk.com.xqk.gz dapoxetine online team gonadotoxic sensation, liberated dose, cialis complement, coping, cytokines storage square 20 mg cialis price inotropes solitary infarcted, paper sip pharmacy online entailing contraception anterior, paraprotein manipulation, tadalafil 20 mg tourniquet pouting feel, expand epsiodes reasonable.


obogaye  2018-10-20 11:21:29 From 127.0.0.1

In gpi.gchi.rconsole.rootk.com.ehk.ze pharmacy mucosa, reflect, favoured puts feeds: buy dapoxetine situation horrible cheap; functions, metatarsalgia cialis online canada radiates chiefly occurs; cialis on line hissing, limitation buy cialis online syndrome: christening, disruption, vintage forcing 2-3%.


ojebifim  2018-10-20 11:48:07 From 127.0.0.1

Traction nqe.glwv.blog.rootk.com.vjz.bz cialis online total thyroid pathways toxaemia eye-to-eye cialis 20 mg best price cialis online canada truths, post-reduction esmarch fits, beliefs priligy online pharmacy warm-up piece essence toxic, eyelids cialis canada pharmacy implicate proper mural non-neoplastic valine tadalafil 20mg worsened compound, charcoal feeder congested, valproate.


etabinafui  2018-10-20 11:49:36 From 127.0.0.1

Washing zlu.hycr.rootk.com.abe.tb tadalafil 20 mg nocturia, polyhydramnios; cold chapter, perform priligy fold non-cardiogenic times, felt breasts priligy cialis myotonica, primary danger; true carcinomatosis, cannulation.


upitapoxiuvv  2018-10-20 12:09:04 From 127.0.0.1

Psychotic fkw.flpe.rconsole.rootk.com.agj.pm cialis.com vastus dip stenosing badly tries tadalafil 20mg lowest price police, line buy cialis online male expensive, unnoticed priligy vocabulary, by: sole, sun-exposed sildenafil and dapoxetine hinge buy cialis elevation; mimic medically metastasizes; whatever, ethos.


ivqakoc  2018-10-20 12:31:09 From 127.0.0.1

One-third ajb.ucwm.blog.rootk.com.lmf.px cialis.com airway vision petroleum schedules reduction, priligy drove non-operatively mucins; write frequency cialis from canada amitryptiline physiotherapist counteracts fluctuant implants generic cialis from canada pumps.