How Can I Remove the ZEROS in a String?

2,807 views
Skip to first unread message

feeling4t

unread,
Jul 31, 2012, 2:24:10 AM7/31/12
to golan...@googlegroups.com
name := make([]byte, 100)
fi.ReadAt(name,  offset )

In the file fi, there are many fixed-length 100 parts, which contain non-fixed-length string, like [ 75 73 65 75 83 00 00 00 00 00 ... ]
when I transform it to string, use string(name), I got a string length 100, which not as expect,  like  C programming language, ignore  the '\0' parts,
I want to remove the zeros, but string.Trim, string.TrimSpace, or string. Field,All of them don't work,  how can I remove the ZEROS?
Thanks


Jesse McNelis

unread,
Jul 31, 2012, 2:33:01 AM7/31/12
to feeling4t, golan...@googlegroups.com
On Tue, Jul 31, 2012 at 4:24 PM, feeling4t <feel...@gmail.com> wrote:
> name := make([]byte, 100)
> fi.ReadAt(name, offset )

ReadAt(p []byte, off int64) (n int, err error)
ReadAt returns the number of numbers read and any error encountered.
You should slice the given buffer up to the number of bytes actually read.
eg.

name := make([]byte, 100)
n,err := fi.ReadAt(name, offset )
if err != nil && err != io.EOF {
//handle errors
}

//slice the buffer to just the number of bytes read.
name = name[0:n]

You can read about the io.ReaderAt interface here,
http://golang.org/pkg/io/#ReaderAt

> In the file fi, there are many fixed-length 100 parts, which contain
> non-fixed-length string, like [ 75 73 65 75 83 00 00 00 00 00 ... ]
> when I transform it to string, use string(name), I got a string length 100,
> which not as expect, like C programming language, ignore the '\0' parts,
> I want to remove the zeros, but string.Trim, string.TrimSpace, or string.
> Field,All of them don't work, how can I remove the ZEROS?
> Thanks
>
>



--
=====================
http://jessta.id.au

Rémy Oudompheng

unread,
Jul 31, 2012, 2:33:49 AM7/31/12
to feeling4t, golan...@googlegroups.com
You could find the index of the NUL byte (using bytes.IndexByte or
strings.IndexRune) and slice it, or use strings.TrimRight(s,
string(0)).

http://play.golang.org/p/FeRpZVg7vt

Rémy.

feeling4t

unread,
Jul 31, 2012, 2:38:36 AM7/31/12
to golan...@googlegroups.com, feeling4t
I try strings.Trim( string(name), string(0) ), it works 
Thank U

在 2012年7月31日星期二UTC+8下午2时33分49秒,Rémy Oudompheng写道:
Reply all
Reply to author
Forward
0 new messages