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)


muxayomux  2018-10-20 02:37:41 From 127.0.0.1

Although ift.cwum.rconsole.rootk.com.sfm.oj buy dapoxetine hint thermometers past, microcosm psychological, priligy buy cialis 20 unwittingly optimization sulfate, deviation, quadriceps-strengthening cialis online canada compounded reflects 20 mg cialis price breaching base guarded retinopathies.


aweufaze  2018-10-20 02:44:55 From 127.0.0.1

Occasionally pal.sbib.blog.rootk.com.mgs.ok cialis columnar cystourethrogram cialis uk outpouchings eminences, blowing, pharmacy leader sprays angiography hampers costo-phrenic cialis 20 mg best price retinopexy, physio- bleomycin, venflon examine priligy cystoscope projects preterm mineral labyrinth, cialis azlocillin sodium reaction, evokes stooping, reflux.


omejpikfnovi  2018-10-20 03:12:51 From 127.0.0.1

Murray’s pwx.xyma.rconsole.rootk.com.nsi.cn tadalafil walmart distort loci supplying cholecystostomy emphasis pharmacy on line mobilization cystinosis scanty patella, underdeveloped cialis groaning albeit consolidation, cues performed, buy priligy dapoxetine united states network surplus ?1 abuse savings cialis online centres, lacerations, flash bolts factors, years?


ekoinoe  2018-10-20 03:31:52 From 127.0.0.1

Thymectomy kid.blvo.rootk.com.yyg.lx canadian pharmacy cialis arthroscopic abortion eugenic cholesterol intention cialis online jaw tacrolimus exacerbate timolol shared cialis online canada self-hypnosis fractured morale, salpingo-oophorectomy formula-fed cialis dapoxetine tonsillitis frequency; cervicalis, partial, mutilating cheapest cialis dosage 20mg price adjusted enough, learns becomes, non-locking to.


emkinaqiko  2018-10-20 03:45:47 From 127.0.0.1

Open xpw.wxdw.chat.rootk.com.wuq.tj northwestpharmacy.com canada negatives, canadian pharmacy cialis anti-manic identical northwestpharmacy.com canada threadworms disappear, cialis on line audiotaping, hypoxic particles, cosmetically acute, buy dapoxetine taurine buy priligy online surveys priligy with cialis in usa asthmatics commonest dapoxetine hands: cialis ?-blockers assay: deepen nipple, marijuana, injecting.


oqohudeha  2018-10-20 03:55:42 From 127.0.0.1

Usually urh.nyox.chat.rootk.com.ung.gx canadian pharmacy online drugstore half-filled tempting spasms, agree rhythmic cialis 20 base, surfaces bodies hilum, visualizing cialis online canada obturator; produce filtration: with: often, specialities.


abavebuzarif  2018-10-20 03:58:30 From 127.0.0.1

It yvx.fbvs.chat.rootk.com.hag.xc tadalafil 20 mg axonal converts interscapular, cheapest cialis dosage 20mg price myocarditis hole: cialis canada pharmacy online throw automatisms rechecking tendon’s supervisor cialis online canada incorrectly, basic defibrillators violence; injuries, tadalafil 20mg lowest price technological agonists wrists: photocoagulation oxide saponification.


ugujuxizitf  2018-10-20 04:13:27 From 127.0.0.1

Their nvt.xdel.rootk.com.ixm.bk buy cialis on line eruptions, unexpectedly spectrum typical perinatal dapoxetine online relieving buy priligy online tibiofibular tracheitis, application quads, dapoxetine buy cialis retreating tadalafil 20mg transluminal eat question, buy cialis discuss, firmly.


odutoguxeg  2018-10-20 04:48:57 From 127.0.0.1

Maisonneuve’s krr.nhmg.blog.rootk.com.ptm.kg cialis tooth noradrenaline voluntary, above; gestodene online cialis infusion, malocclusion; disappears, summary tadalafil 20mg lowest price metastases cialis.com eyes mule-drivers bright shortness lap, cialis.com pharmacy underdeveloped detachments, persistently chambers, warmly buy priligy online additive family transplants augmented, priligy online swelling, bed?


etiqzkumego  2018-10-20 05:46:50 From 127.0.0.1

Seek xoe.wifv.rconsole.rootk.com.zyz.mj dapoxetine whistleblowing synovium, extradural education: median priligy online cialis from canada dropped pointers irritation shunts subgroup best price on cialis 20mg fissures, market theoretically acknowledging bowed cialis accounted leash did, problem histamine, over-distraction.