Converting NULL terminated []byte to []string

3,348 views
Skip to first unread message

Dave Cheney

unread,
Feb 11, 2011, 5:12:22 AM2/11/11
to golang-nuts
Can anyone suggest a pragmatic way to convert a []byte of NULL
terminated strings to a []string. I'm hoping there is some code in the
standard library that I can leverage.

Cheers

Dave

Jan Mercl

unread,
Feb 11, 2011, 5:18:20 AM2/11/11
to golan...@googlegroups.com
I think e.g.
will by useful. 

Dave Cheney

unread,
Feb 11, 2011, 5:25:10 AM2/11/11
to golan...@googlegroups.com
Thanks for the tip Jan, this is what I came up with

func stringzToString(buff []byte) (l []string) {
l = make([]string, 1, 0)
for _, s := range bytes.Split(buff, []byte { 0 }, -1) {
l = append(l, string(s))
}
return
}

Comments and suggestions welcome (except the horrid function name,
i'll think of something better)

Jan Mercl

unread,
Feb 11, 2011, 5:32:14 AM2/11/11
to golan...@googlegroups.com
On Friday, February 11, 2011 11:25:10 AM UTC+1, Dave Cheney wrote:

func stringzToString(buff []byte) (l []string) {
l = make([]string, 1, 0)
for _, s := range bytes.Split(buff, []byte { 0 }, -1) {
l = append(l, string(s))
}
return
}

Comments and suggestions welcome (except the horrid function name,
i'll think of something better)

func stringzToString(buff []byte) (l []string) { // not tested at all
    x := bytes.Split(buff, []byte{0}, -1)
    l = make([]string, len(x)
    for i, b := range x {
        l[i] = string(b)
    }
    return
}

roger peppe

unread,
Feb 11, 2011, 5:41:30 AM2/11/11
to golan...@googlegroups.com
Split probably isn't exactly what you want because
it leaves an empty string after the final '\0'.

Here are two versions that are pretty much equivalent
(actually the second one will ignore a non-null-terminated
string at the end of b, which might or might not
be what you want).

The second is probably a little faster (bytes.Split could
perhaps get a special case for a 1-byte separator)

var zb = []byte{0}
func NullTermToStrings(b []byte) (s []string) {
for _, x := range bytes.Split(b, zb, -1) {
s = append(s, string(x))
}
if len(s) > 0 && s[len(s)-1] == "" {
s = s[:len(s)-1]
}
return
}

func NullTermToStrings(b []byte) (s []string) {
for {
i := bytes.IndexByte(b, '\0')
if i == -1 {
break
}
s = append(s, string(b[0:i]))
b = b[i+1:]
}
return

Reply all
Reply to author
Forward
0 new messages