convert multi line string to single line

Viewed 6854

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.

5 Answers

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!

Because it is the first Google result at "Scala multiline to a single line" and the question is pretty general. It may be reasonable to add an implicit way:

implicit class StringExtensionImplicits(s: String) {

    def singleLine: String = {
      singleLine('|')
    }

    def singleLine(marginChar: Char): String = {
      s.stripMargin(marginChar).replace('\n', ' ')
    }

}

Now you can:

logger.info(
  """I'm a so long log entry that some devs who like vim don't like me.
    |But you can help them to keep patience.""".singleLine)

If someone want to find how to create multiline strings:

val myString = "This is " +
               "my string"

which output is This is my string. You can also use s strings here to implement variables

Related