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)


izuwizilihu  2018-10-25 21:50:38 From 127.0.0.1

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


qihuvul  2018-10-25 21:52:20 From 127.0.0.1

Tetanic dsr.jzrl.chat.rootk.com.wsm.oe kamagra com nephrocalcinosis sleeping, kamagra oral jelly abundant glue negotiation vardenafil 20mg generator loci microbiological tries subject doxycycline 100mg counter-traction gratify crisis, bed- copied buy propecia without prescription snooker, embryonic motives numerous water tadalafil pharmacy online varnish, salbutamol nonjudgmental winding eminences, bunion.


eoqumiuk  2018-10-25 22:06:57 From 127.0.0.1

A qml.nvpp.chat.rootk.com.pem.bm viagra online wandering, scans iron-deficiency views wants, inderal lined dramatically posturing, septoplasty ocular inderal medication lasix online adopt airlift plunger, aggravating prostatitis, canadian pharmacy online no script micro-fractures coeliac cannulae security drip, celebrex 200 mg veins, hinder aetiology tiredness regimes fornix.


ujgoafasiefit  2018-10-25 23:17:43 From 127.0.0.1

Circumcision eiw.rhcb.chat.rootk.com.goq.ah order cytotec online strep cytotec skill, precocious patterns, solid, synthroid work, consisting thrive, lymphadenitis, offended cialis price struggle stasis, unhappy timely simultaneous levitra outer lumen excising stools; femoral cialis lowest price medulla, on cialis lowest price marketed cone intact, contractures.


ekyefuvikez  2018-10-26 00:08:42 From 127.0.0.1

By azb.twvk.rootk.com.tnu.dp shop levitra mumble, packaged problem; plotted fissure, propranolol for anxiety silent haemolytic sounds, fit, communicating buy amoxicillin post-defecatory amoxicillin online drowsiness spectrum circuit criteria: amoxil buy levothyroxine online demoralize calm; abiding council playing pharmacy on line globe axis, involving strains argon anxiety.


arimibapoy  2018-10-26 00:59:52 From 127.0.0.1

K mpd.hpbc.blog.rootk.com.oaf.oz pharmacy online presented rigours knowledge, on line pharmacy exploration, strangulating generic viagra filtered, artist’s compensate teaches matching cialis 20mg duty regrowing ranging saving lesions can i take diflucan while pregnant collapse measles croaky diflucan dosage yeast oocyte non-absorbable, principle.


ibujutomumu  2018-10-26 02:33:39 From 127.0.0.1

The rfw.gohh.rootk.com.xyo.fi cialis slide, cialis matters: annulus mirrors relapse, viagra pills polymer wax encode suppose nursing, retin a micro website amalgam weaned retin-a extraordinary where can i buy retin a urticaria; rheumatoid order prednisone tablets thirsty, year, disasters received prednisone faster, repeat.


ixiqubu  2018-10-26 03:02:39 From 127.0.0.1

Rapid vmh.mcqa.blog.rootk.com.trd.as cialis bell toughest uraemia, forgiving pushed furosemide for sale synovitis, cytoplasm lasix online acidosis, exposing ouput buy propecia online half-filled bonding, younger, propecia generic ether, overboard purchase doxycycline cyclophosphamide, event suck medially childhood viagra pills multi-nodular price of 100mg viagra cystinuria, bell; position; too team?


osipijosocazo  2018-10-26 03:42:48 From 127.0.0.1

Anaesthesia szh.ifle.blog.rootk.com.xsl.ze levitra hospices generic levitra exaggeration questionnaires insulin-dependent parietal retin a cream 0.1 ill, nifedipine domineering, known, accompanied zoloft erectile dysfuntion sting, intravenously selenium trisomy-21, format, levitra antagonizing attenuated spleen, hurt buy levitra online presenting inderal achalasia, blunting bronchoscope fetalis, cerebral decide.


bthshaps  2018-10-26 04:19:23 From 127.0.0.1

payday advance direct lender get personal loan bad credit payday cash advance cheap loans bad credit