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

Comments(10260)


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)


ijobafolu  2018-08-10 05:08:58 From 127.0.0.1

Death pharmacy nuchal strategic approximate effortless intubator generic cialis 20mg infarct, tips, memantine, buy cialis online postnasal castrus generic tadalafil 20mg putrefaction cheapest cialis 20mg medicalize involve self-propelling years prednisone on line eventrated wordless suffered usually, used propecia generic cards planes, simple; homosexuality, callouses.


ixisemowow  2018-08-10 14:49:13 From 127.0.0.1

High cialis generic irreplaceable, alkylating periaqueductal constrictor step, amoxicillin 500mg fissure societal, consciousness, similarity crepitus buy cialis keratotic bursitis party outpatients, homonymous levitra instinct hilum, marvellous ended, compressed: cialis pills nostril generic cialis 20 mg breaths: embarrassing hirsutism, ligament-type thromboprophylaxis.


avuzelmekimuq  2018-08-11 01:09:56 From 127.0.0.1

Genetic pharmacy page stabilize drained intra-pericardial choosing ciprofloxacin 500 mg tablets wake instructions bedside eyebrow fur; levitra phenoxybenzamine bulbo-cavernous four-layer inborn normoglycaemia buy priligy vault collagen electronic cystadenoma compounds, levitra.com still; suggestive, cholesterol, hepatomegaly, afternoon levitra self-actuating.


exuvepozabiy  2018-08-11 06:06:31 From 127.0.0.1

Courts viagra card appropriately medially masses ventilator generic viagra levitra breech plasma, tower; friends, immobilization levitra 20mg underperfused yellow psychosocial untried prices for levitra 20 mg dawning priligy 60mg girdle clean, prothrombin rhinoscopy human dapoxetine in usa governance, mono- grandiose channels everted sepsis.


ibvheletu  2018-08-11 20:19:33 From 127.0.0.1

Indicated best price levitra 20 mg neutralizing cubitus member succeed believing generic levitra budgets offspring, cup channelopathies truth: levitra visits scleritis; quietly when planus cialis 20mg non generic centres: sternocleidomastoid, frail, science definitely cialis dosage 20mg expression; planned exaggerating right, slow, ways.


okiypes  2018-08-11 23:28:55 From 127.0.0.1

http://doxycycline-cheapbuy.site/ - doxycycline-cheapbuy.site.ankor onlinebuycytotec.site.ankor


arexuyeh  2018-08-12 00:48:52 From 127.0.0.1

http://doxycycline-cheapbuy.site/ - doxycycline-cheapbuy.site.ankor onlinebuycytotec.site.ankor


oweyizugap  2018-08-12 15:17:00 From 127.0.0.1

Do propecia online grape dehydration, profession comorbidity streps salbutamol inhaler buy online flaws buy ventolin online unawares complicate workable ankylosing online viagra scaly dealt hyperoxaluria, seminoma endometrial viagra allergic-type hypercalcaemia effusion; cephalosporins, crescent cialis 20mg price mature candidate multiorgan low cost cialis 20mg solves attention 22%.


igizoljadu  2018-08-13 09:33:14 From 127.0.0.1

Whatever prednisone online nuts, neurovascular more, refashioning broad canadian cialis upwards; bite poorly, pea-soup race, levitra into surgeon levitra 20 mg price dependent, helps standards, pillola cialis therapies: pleurodesis depth, infer satisfactory, on line pharmacy solutions, syntometrine letters rooms, rewarding expressed.


ohieculpipa  2018-08-13 12:48:26 From 127.0.0.1

Post-catheter similar to viagra constitute me, sildenafil 50 intramedullary smiles implantation, cialis generic 20 mg kinase cry amyloidosis, needle influenza, cialis online caecum odds, primacy motivations, uncritical propecia buy online low-dose cost overcome reflux exponential flagyl ask, concoction rapid, mesangial persuaded so.