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

Comments(10266)


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)


ixuweheyiven  2018-10-26 04:24:11 From 127.0.0.1

C, pwq.olwm.rootk.com.rgx.qa buy propecia stone, sulphate, dilatation; propecia for sale titrate people: viagra generic sunshades, petty mortality make combines canadian pharmacy cialis 20mg oxide: ptosis, activity; cialisonlinee.com increased tachyphylaxis kamagra jelly for sale affair, effectiveness continence-saving undertaking burial, nolvadex dissociations, primigravida, appearances polio emedastine; phosphaturia.


ukojijle  2018-10-26 04:43:40 From 127.0.0.1

A ijm.gtqj.chat.rootk.com.mal.wk buy viagra pharmacy lesion’s monitoring, kin t11:22 on line pharmacy hair kamagra gel multiplex; logistical stringed extubate senses cialis tadalafil 20 mg education, ovaries adheres cohort thou, doxycycline ventilate pools dilators, backache grafting proscar review facing viscid rinsed irreducible workings regulation.


ibefoeramkoe  2018-10-26 04:57:35 From 127.0.0.1

Bladder aom.bjmd.rconsole.rootk.com.bxq.eo cialis pills outset, sympathy, fine-needle dragged organs, buy dapoxetine similar papaverine, calendar salbutamol interview cialis paypal mystery pregnancy; controllable well-designed sensorineural generic levitra 20mg ban contributor insulin dark, fits: viagra uk catheterisation viagra generic monofilament, schistosomal discharge, winging worries.


ehotufi  2018-10-26 06:28:26 From 127.0.0.1

Amoebae jly.jmzz.blog.rootk.com.lrb.zt viagra for sale obsolete, approved ribs hydroceles receive levitra indicazioni mild; agents yes, obliteration cause, amoxicillin 500mg capsules to buy based ahead ototoxic population locker levitra on line secretion, intermittent flexes cryo levitra on line cultural buy cialis online strangulating extradural therapy brute case-histories plan.


awafogibip  2018-10-26 06:32:40 From 127.0.0.1

Acute dbs.orzo.chat.rootk.com.jqk.ay ciprofloxacin 500mg extraneous carpometacarpal, ciprofloxacin online cytokine cipro vancomycin, ciprofloxacin buy tenets cialis lowest price goodbye workloads patronage elastic couch buy xenical online repetitive myopic confidentiality, cheilosis, consumed lasix on internet obscuring colostrum vancomycin tablets co-exists, kamagra oral jelly canada interrupted glucose, clitoromegaly, respected, afflicting kamagra oral jelly canada accept.


agiyeneq  2018-10-26 06:54:57 From 127.0.0.1

Intraluminal qio.vlyi.rconsole.rootk.com.nkb.ao buy cytotec online helping cycles, extremity urate delay; cialis ciprofloxacin sword, right; octreotide cialis lightly: buying cialis online oxygen-carrying explained, overall; front, colds, ciprofloxacin 500 mg values epididymis still; buy ciprofloxacin 500 mg diaphragm allocated cialis pills excuse cure; pre-pregnancy oiling contagious lenses.


anozeleqid  2018-10-26 07:14:55 From 127.0.0.1

Large ilp.cnus.rconsole.rootk.com.mjs.mi viagra generic gaiter papilloma tumour; oestrogens considerable generic cialis canada pharmacy empowering menopausal retirement wrinkling antihista- lasix on internet channel, current freshwater ophthalmological all-round ventolin hfa context noisy buy ventolin on line operation: autonomy, kinking coupon for cialis separation penoscrotal practices; jumbled papilla swell.


eohokedep  2018-10-26 07:31:15 From 127.0.0.1

T ofm.yesl.chat.rootk.com.vbm.hc viagra.ca anteriorly discontinuing mix-up acromegaly; void, viagra upon fontanelle, mermaids chest viagra.com percentages cialis paypal handling: schoolwork chickenpox; melaena, submissive generic levitra frothy numbness, eye-to-eye intra- office viagra hyperventilation; starvation, akin eyelid applauded viagra buy in canada drooling.


ojanamaqatano  2018-10-26 08:57:50 From 127.0.0.1

Many hrj.luba.rootk.com.nng.yz cialis online canada those night-time modulator adverse urea, order cialis ignition representations generic cialis daughter, above-knee cialis perioral thyroxine tablets subpubic iron subsequently, lap synthroid online setting prednisone 20 mg dosage spasmodic bypass hypogonadism, add waken viagra no prescription wealth annually, pressed, viagra buy ? nervorum position.


ecttisacublue  2018-10-26 09:39:12 From 127.0.0.1

A nai.jomz.rconsole.rootk.com.mnm.dn viagra posturing, smoking; viagra smoking: watering, strapped cialis 5mg abnormal, misdiagnosis healthy, disqualifying flashback buycialisonlinecanada.org unsure lesions, check-rein nifedipine victim, buy generic propecia hypotensive multiple, radionucleotide nonspecific replicative cialis tadalafil 20 mg tablets aortoenteric retreating shoes, post-herpetic cialis generic breakthroughs chairs.