Use of () method:
- mkString(seq:String) method is to split the original string using a specific string seq.
- mkString(statt:String,seq:String,end:String) method is to split the original string using a specific string seq while adding the string start before the original string and add the string end after it.
object Test { def main(args: Array[String]): Unit = { var name : String = "Hello LittleLawson" var age :Int = 2 println() println((" "))//separate string with space var str0 = "scala" println((","))//separate string with comma println(("begin",",","end")) /* is used in the inner List,That is say ,Elements in the list is applied. */ val a = List(1,2,3,4) val b = new StringBuilder() println(("List(" , ", " , ")")) } }
The execution results are as follows:
Hello LittleLawson
H e l l o L i t t l e L a w s o n
s,c,a,l,a
begins,c,a,l,aend
List(1, 2, 3, 4)Process finished with exit code 0
Convert a collection into a string through the mkString method
Problem
If you want to convert collection elements into strings, you may also add delimiters, prefixes, and suffixes.
Solution
Use the mkString method to print a collection content. Here is a simple example:
scala> val a = Array("apple", "banana", "cherry") a: Array[String] = Array(apple, banana, cherry) scala> res3: String = applebananacherry
Use the mkString method to see that the result is not beautiful, let's add a separator:
scala> (",") res4: String = apple,banana,cherry scala> (" ") res5: String = apple banana cherry
This will look much better, and you can also add a prefix and a suffix:
scala> ("[", ", ", "]") res6: String = [apple, banana, cherry]
If you want to convert an abscond collection into a string, such as a nested array, first you need to expand the nested array and then call the mkString method:
scala> val a = Array(Array("a", "b"), Array("c", "d")) a: Array[Array[String]] = Array(Array(a, b), Array(c, d)) scala> (",") res7: String = a,b,c,d
Discussion
You can call the toString method of the collection, but it returns the name of the collection with the information of the collection element:
scala> val v = Vector("apple", "banana", "cherry") v: [String] = Vector(apple, banana, cherry) scala> res8: String = Vector(apple, banana, cherry)
The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.