Scala program to convert Array to string

Scala | Converting array to string: Here, we are going to learn how to convert an array to string in Scala programming language?
Submitted by Shivang Yadav, on April 12, 2020 [Last updated : March 10, 2023]

Scala | Converting array to string

Arrays play an important role in programming as they provide easy operation and there is a large amount of method available in the Scala library of array manipulation. But there are times when storing or printing of array can be done more effectively when converted to a string, but the question is how? So, here is a program to convert array to string in Scala.

The mkString() method of the array library is employed to perform the task of conversion of array to string.

Syntax

    array_name.mkString(saperator)

The method takes a separator as a parameter which will separate two array elements in the string and returns a string.

Example 1: Scala code to convert array to string

object myObject {
    def main(args: Array[String]) {
        val myArray = Array("Learn", "programming", "at", "IncludeHelp") 
        val str = myArray.mkString(" ")
        print("myArray : "+str)
    }
}

Output

myArray : Learn programming at IncludeHelp

You can use any string as a separator for your converted string, in the above program we have used a single space as a separator which is commonly used. Common separators that are used in converting an array to string are , , \n (new line), "".

In the case of converting an array to string whose elements are numbers, we use , comma as separator else all the elements will appear like a single big number.

Example 2: Scala code to convert array to string

object myObject {
    def main(args: Array[String]) {
        val myArray = Array(12, 5, 45, 56) 
        val str = myArray.mkString(", ")
        print("myArray : "+str)
    }
}

Output

myArray : 12, 5, 45, 56

Scala Array Programs »



Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.