2016-11-12 95 views
0

我無法將索引的字節序列轉換爲以utf-8編碼的字符串。如何在Scala中有效地將IndexedSeq [Byte]轉換爲utf-8字符串

scala> val x : IndexedSeq[Byte] = IndexedSeq(64.toByte, 64.toByte, 64.toByte) 
scala> x.mkString 
res2: String = 748464 

現在我可以使它工作,通過轉換爲數組,然後構建一個新的字符串像這樣;

scala> new String(x.toArray) 
res3: String = [email protected] 

但分配和複製兩次似乎是一個矯枉過正。

有沒有更好的方法?

回答

2

你想要使用指定一個字符集的構造函數。

但是你不能避免複製到String的基礎值,即使是從StringBuilder。

另一個想法可能是反序列化,但你仍然得到緩衝和額外的處理來處理字節。

爲了好玩:

scala> val x : IndexedSeq[Byte] = IndexedSeq(65.toByte, 65.toByte, 65.toByte) 
x: IndexedSeq[Byte] = Vector(65, 65, 65) 

scala> import collection.generic.CanBuildFrom 
import collection.generic.CanBuildFrom 

scala> val cbf = new CanBuildFrom[IndexedSeq[Byte], Char, String] { 
    | def apply(from: IndexedSeq[Byte]) = apply() 
    | def apply() = StringBuilder.newBuilder 
    | } 
cbf: scala.collection.generic.CanBuildFrom[IndexedSeq[Byte],Char,String]{def apply(from: IndexedSeq[Byte]): StringBuilder; def apply(): StringBuilder} = [email protected] 

scala> x.map(_.toChar)(cbf) 
res0: String = AAA