scala 字符串转换数组
String in Scala is a sequence of characters. And, Byte Array in Scala is an array that stores a collection of binary data.
Scala中的String是一个字符序列。 而且,Scala中的字节数组是一个存储二进制数据集合的数组。
字符串到字节数组的转换 (String to byte Array Conversion)
We can convert a string to byte array in Scala using getBytes() method.
我们可以使用getBytes()方法将字符串转换为Scala中的字节数组。
Syntax:
句法:
string.getBytes()
This will return a byte array.
这将返回一个字节数组。
程序将字符串转换为字节数组 (Program to convert string to byte Array)
Program 1:
程序1:
// Program to convert string to Byte Array
object MyClass {
def main(args: Array[String]) {
val string : String = "IncludeHelp"
println("String : " + string)
// Converting String to byte Array
// using getBytes method
val byteArray = string.getBytes
println("Byte Array :" + byteArray)
}
}
Output:
输出:
String : IncludeHelp
Byte Array :[[email protected]
Explanation:
说明:
In the above code, we have used the getBytes method to convert the string to byte array and then printed the byteArray using the println() method which gives the pointer value.
在上面的代码中,我们使用了getBytes方法将字符串转换为字节数组 ,然后使用println()方法打印了byteArray ,该方法给出了指针值。
Program 2:
程式2:
// Program to convert string to Byte Array
object MyClass {
def main(args: Array[String]) {
val string : String = "IncludeHelp"
println("String : " + string)
// Converting String to byte Array
// using getBytes method
val byteArray = string.getBytes
// printing each value of the byte Array
println("Byte Array : ")
for(i <- 0 to byteArray.length-1)
print(byteArray(i) + " ")
}
}
Output:
输出:
String : IncludeHelp
Byte Array :
73 110 99 108 117 100 101 72 101 108 112
Explanation:
说明:
In the above code, we have created a String named string with value "IncludeHelp" and then used the getBytes to convert it into a byte Array then printed the elements of the array using for loop.
在上面的代码中,我们创建了一个名为string的字符串 ,其值为“ IncludeHelp”,然后使用getBytes将其转换为字节数组,然后使用for循环打印该数组的元素。
翻译自: https://www.includehelp.com/scala/how-to-convert-a-string-to-byte-array-in-scala.aspx
scala 字符串转换数组