Home » Scala » Scala array programs

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

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.

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





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.