Trimming byte array when converting byte array to string in Java/Scala

arrays, java, scala, string

Solution

Assuming that `0: Byte` is a trailing value, then

implicit class RichToString(val x: java.nio.ByteBuffer) extends AnyVal {
  def byteArrayToString() = new String( x.array.takeWhile(_ != 0), "UTF-8" )
}

Hence for

val x = ByteBuffer.allocate(10).put("Hello".getBytes())

x.byteArrayToString
res: String = Hello

Problem

Using ByteBuffer, I can convert a string into byte array: ``` val x = ByteBuffer.allocate(10).put("Hello".getBytes()).array() > Array[Byte] = Array(104, 101, 108, 108, 111, 0, 0, 0, 0, 0) ``` When converting the byte array into string, I can use `new String(x)`. However, the string becomes `hello?????`, and I need to trim down the byte array before converting it into string. How can I do that? I use this code to trim down the zeros, but I wonder if there is simpler way. ``` def byteArrayToString(x: Array[Byte]) = { val loc = x.indexOf(0) if (-1 == loc) new String(x) else if (0 == loc) "" else new String(x.slice(0,loc)) } ```

Original source

Related problems