[英]convert a list of String to a string
I have the following list in input and : 我在输入中有以下列表:
val list=List("aimee,Paris,10",
"alex,Nice,12",
"Sara,Paris,15")
and I want to have a multiline String as output with the following format: 并且我想以以下格式输出多行字符串:
val output:String="aimee Paris,
alex Nice,
Sara Paris")
I wrote the following code 我写了下面的代码
def listToMultLine (input:List[String]):String ={
input.map(_.split(",")).map(x => List(x(0),x(1)).mkString(","))
}
but this gives me erronous output thanks a lot for your help 但这给了我错误的输出,非常感谢您的帮助
.mkString
is the solution for you which would concat all the elements in a collection to a String. .mkString
是适合您的解决方案,可以将集合中的所有元素.mkString
为String。
But looking at your output suggests that you want to remove the last digit and want each element in next line of the string. 但是查看您的输出表明您想要删除最后一位数字,并希望字符串的下一行中的每个元素。
So following should get you your desired output 因此,以下应该可以为您提供所需的输出
scala> list.map(x => x.substring(0, x.lastIndexOf(","))).mkString(", \n")
res0: String =
aimee,Paris,
alex,Nice,
Sara,Paris
It seems you want to omit the last digit, so I would to suggest to use this solution, which is more readable than Ramesh's similar solution thanks to pattern-matching: 似乎您想省略最后一位数字,因此我建议您使用此解决方案,由于模式匹配,该解决方案比Ramesh的类似解决方案更具可读性:
list.map(s => {
val Seq(name,city,age) = s.split(',')
(name,city)
}).mkString(", \n")
or alternatively 或者
list.map(s => s.split(','))
.map{case Seq(name,city,age) => (name,city)}
.mkString(", \n")
res0: String = (aimee,Paris),
(alex,Nice),
(Sara,Paris)
Try This: 尝试这个:
list.map(_.split(",")).map{case Array(a,b,c)=>a+" "+b}.mkString(",\n")
scala> val list=List("aimee,Paris,10", "alex,Nice,12", "Sara,Paris,15")
list: List[String] = List(aimee,Paris,10, alex,Nice,12, Sara,Paris,15)
scala> list.map(_.split(",")).map{case Array(a,b,c)=>a+" "+b}.mkString(",\n")
res62: String =
aimee Paris,
alex Nice,
Sara Paris
scala>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.