ratnaraj
ratnaraj

Reputation: 1

how to append char at start and end of each element in scala seq?

I am trying some string manipulation on sequence

I have sequence of elements ex: Seq("aaa","bbb","ccc") and need to be converted to String with appending some characters to start and end of each element

result should be string -> "aaa","bbb","ccc"

scala> val initial = Seq("aaa","bbb","ccc")

initial: Seq[String] = List(aaa, bbb, ccc)

scala> initial.foldLeft(Seq [String] ()){(z,x)=>z:+("\""+x+"\""+",")}

res2: Seq[String] = List("aaa",, "bbb",, "ccc",)

Any suggestions?

Upvotes: 0

Views: 1171

Answers (3)

CervEd
CervEd

Reputation: 4243

This can also be achieved using only mkString(start, sep, end)

https://www.scala-lang.org/api/2.12.3/scala/collection/immutable/List.html#mkString(start:String,sep:String,end:String):String

List("aaa", "bbb", "ccc").mkString("\"", "\",\"", "\"")

Upvotes: 3

Abhi
Abhi

Reputation: 130

You don't need a foldLeft to transform elements.

Try this

initial.map(x=> s""""${x}"""").mkString(",")

Upvotes: 1

You probably just want to do this:

def appndAndPrependTo[A](data: Seq[A])(s: String): Seq[String] =
  data.map(a => s"${s}${a}${s}")

Upvotes: 1

Related Questions