Q:

Scala program to convert Array to string

belongs to collection: Scala Array Programs

0

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.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program:

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.

Program:

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

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Scala Array Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Scala program to convert multiline strings to an a... >>
<< Scala program to create strings array...