scala 字符串转换数组_如何在Scala中将字符串转换为字节数组?

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 字符串转换数组

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值