7

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.

Mario Galic
  • 47,285
  • 6
  • 56
  • 98
coder25
  • 2,363
  • 12
  • 57
  • 104

6 Answers6

5

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

Ramesh Maharjan
  • 41,071
  • 6
  • 69
  • 97
3

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!
Mario Galic
  • 47,285
  • 6
  • 56
  • 98
1

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)
0

Try this

myString.split("\n").filter(_.nonEmpty).mkString("",";",";")
Dhirendra
  • 289
  • 3
  • 8
0

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

Yauheni Leaniuk
  • 418
  • 1
  • 6
  • 15
0

You can use

    val myString =
      """
        |a=b
        |c=d
        |""".stripMargin.lines.mkString(";")

linesIterator is deprecated since scala 2.11

Ayoub Omari
  • 806
  • 1
  • 7
  • 24