scala 字符串轉換數組
Byte Array in Scala is an array of elements of a byte type. String in Scala is a collection of the character data type.
Scala中的字節數組是字節類型的元素的數組。 Scala中的String是字符數據類型的集合。
將字節數組轉換為字符串 (Convert byte array to string)
For converting a byte array to string in Scala, we have two methods,
為了在Scala中將字節數組轉換為字符串,我們有兩種方法,
Using new keyword
使用新關鍵字
Using mkString method
使用mkString方法
1)使用new關鍵字將字節數組轉換為字符串 (1) Converting byte array to string using new keyword)
In this method, we will convert the byte array to a string by creating a string using the new String() and passing the byte array to the method.
在此方法中,我們將通過使用新的String()創建字符串并將字節數組傳遞給該方法,將字節數組轉換為字符串。
Syntax:
句法:
val string = new String(byte_array)
Program to convert a byte array to string
程序將字節數組轉換為字符串
// Program to convert Byte Array to String
object MyObject {
def main(args: Array[String]) {
val byteArray = Array[Byte](73, 110, 99, 108, 117, 100, 101, 104, 101, 108, 112)
val convertedString = new String(byteArray)
println("The converted string '" + convertedString + "'")
}
}
Output:
輸出:
The converted string 'Includehelp'
Explanation:
說明:
In the above code, we have created a byte array named byteArray and converted it to a string by passing the byteArray while creating a string named convertedString using new String().
在上面的代碼中,我們創建了一個名為byteArray的字節數組,并在使用new String()創建一個名為convertedString的字符串的同時,通過傳遞byteArray將其轉換為字符串。
2)使用mkString方法將字節數組轉換為String (2) Converting byte array to String using mkString method)
We can use the mkString method present in Scala to create a string from an array. But prior to conversion, we have to convert byte array to character array.
我們可以使用Scala中存在的mkString方法從數組創建字符串。 但是在轉換之前,我們必須將字節數組轉換為字符數組。
Syntax:
句法:
(byteArray.map(_.toChar)).mkString
Program to convert byte array to String using mkString method
程序使用mkString方法將字節數組轉換為String
// Program to convert Byte Array to String
object MyObject {
def main(args: Array[String]) {
val byteArray = Array[Byte](73, 110, 99, 108, 117, 100, 101, 104, 101, 108, 112)
val convertedString = byteArray.map(_.toChar).mkString
println("The converted string '" + convertedString + "'")
}
}
Output:
輸出:
The converted string 'Includehelp'
Explanation:
說明:
In the above code, we have used the mkString method to convert a byte array to string. We have created a byte Array named byteArray and then used the mkString method to convert it to a string. But before conversion, we have converted the byte to their character equivalent using .map(_.toChar) method. The result of this is stored to a string named convertedString which is then printed using println method.
在上面的代碼中,我們使用了mkString方法將字節數組轉換為字符串。 我們創建了一個名為byteArray的字節數組,然后使用mkString方法將其轉換為字符串。 但是在轉換之前,我們已經使用.map(_。toChar)方法將字節轉換為等效的字符。 其結果存儲到一個名為convertedString的字符串中,然后使用println方法打印該字符串。
翻譯自: https://www.includehelp.com/scala/how-to-convert-byte-array-to-string-in-scala.aspx
scala 字符串轉換數組