Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert multi line string to single line

Consider the following snippet

val myString =
  """
    |a=b
    |c=d
    |""".stripMargin

I want to convert it to a single line with delimiter ;

a=b;c=d;

I tried

myString.replaceAll("\r",";")

and

myString.replaceAll("\n",";")

but it didn't work.

like image 828
coder25 Avatar asked Aug 15 '17 08:08

coder25


2 Answers

I tried with \n and it works

scala> val myString = """
     | a=b
     | c=d
     | """.stripMargin
myString: String =
"
a=b
c=d
"

scala> myString.replaceAll("\n",";")
res0: String = ;a=b;c=d;

scala> res0.substring(1, myString.length)
res1: String = a=b;c=d;

I hope it helps

like image 199
Ramesh Maharjan Avatar answered Oct 17 '22 04:10

Ramesh Maharjan


Based on https://stackoverflow.com/a/25652402/5205022

"""
  |a=b
  |c=d
  |""".stripMargin.linesIterator.mkString(";").trim

which outputs

;a=b;c=d

or using single whitespace " " as separator

"""
  |Live long
  |and
  |prosper!
  |""".stripMargin.linesIterator.mkString(" ").trim

which outputs

Live long and prosper!
like image 3
Mario Galic Avatar answered Oct 17 '22 03:10

Mario Galic