Alex Rivera | Logout

Removing NUL characters from bytes

Asked 2013-03-15T11:30:44.973
40

To teach myself Go I'm building a simple server that takes some input, does some processing, and sends output back to the client (that includes the original input).

The input can vary in length from around 5 - 13 characters + endlines and whatever other guff the client sends.

The input is read into a byte array and then converted to a string for some processing. Another string is appended to this string and the whole thing is converted back into a byte array to get sent back to the client.

The problem is that the input is padded with a bunch of NUL characters, and I'm not sure how to get rid of them.

So I could loop through the array and when I come to a nul character, note the length (n), create a new byte array of that length, and copy the first n characters over to the new byte array and use that. Is that the best way, or is there something to make this easier for me?

Some stripped down code:

data := make([]byte, 16)
c.Read(data)

s := strings.Replace(string(data[:]), "an", "", -1)
s = strings.Replace(s, "\r", "", -1)
s += "some other string"
response := []byte(s)
c.Write(response)
c.close()

Also if I'm doing anything else obviously stupid here it would be nice to know.

go
Edit
Report

1 Answer

81

In package "bytes", func Trim(s []byte, cutset string) []byte is your friend:

Trim returns a subslice of s by slicing off all leading and trailing UTF-8-encoded Unicode code points contained in cutset.

// Remove any NULL characters from 'b'
b = bytes.Trim(b, "\x00")
answered 2013-03-15T11:43:26.593

Your Answer