Scalaの複数行の文字列



Scala Multi Line String



Scala ''' Wayで使用して、複数行の文字列を作成できます。

object StringTest { def main(args: Array[String]): Unit = { val s1 ='''This is my first time to learn Scala''' println(s1) } }

出力は次のとおりです。



This is my first time to learn Scala

ただし、この方法には問題があります。つまり、各行の先頭にスペースが含まれている可能性があります。スペースを削除する方法は、複数行の文字列の最後に追加できます。stripMarginメソッド、および前に追加2行目から始まる各行|、例:

object StringTest { def main(args: Array[String]): Unit = to learn Scala'''.stripMargin println(s1) }

出力は次のとおりです。



This is my first time to learn Scala

|を使用しない場合は、他の文字を使用することもできます。

object StringTest { def main(args: Array[String]): Unit = { val s2 ='''This is #my first time #to learn Scala'''.stripMargin('#') println(s2) } }

出力は次のとおりです。

This is my first time to learn Scala

ここでは、stripMargin( '#')の代わりにstripMargin( '#')しか使用できないことに注意してください。これは表示されますCannot resolve reference stripMargin with such signature
各改行文字列の間に実際に生成されたScalaの複数の行 改行は置き換えることができます。



val s3 ='''This is #my first time #to learn Scala'''.stripMargin('#').replaceAll(' ', ' ') println(s3)

出力は次のとおりです。

This is my first time to learn Scala

この置換に注意を払う必要があるのは、エディターで使用する必要があるということです。replaceAll(' ', ' ')しかしscalaではREPL使用する必要があるのはreplaceAll(' ', ' ')理由は次のとおりです。

Your Idea making the newline marker the standard Windows , so you've got 'abcd efg'. The regex is turning it into 'abcd efg' and Idea console is treaing the slightly differently from how the windows shell does. The REPL is just using as the new line marker so it works as expected. Solution 1: change Idea to just use newlines. Solution 2: don't use triple quoted strings when you need to control newlines, use single quotes and explicit characters. Solution 3: use a more sophisticated regex to replace , , or

Scalaの複数行の文字列のもう1つの機能は、一重引用符と二重引用符をエスケープする必要がないことです。

val s4 ='''This is #'my' first time #to 'learn' Scala'''.stripMargin('#').replaceAll(' ', ' ') println(s4)

出力は次のとおりです。

This is 'my' first time to 'learn' Scala

stripMargin関数in StringLike.scalaソースコードがデフォルトで使用されます。|この文字列

/** For every line in this string: * * Strip a leading prefix consisting of blanks or control characters * followed by `|` from the line. */ def stripMargin: String = stripMargin('|') /** For every line in this string: * * Strip a leading prefix consisting of blanks or control characters * followed by `marginChar` from the line. */ def stripMargin(marginChar: Char): String = { val buf = new StringBuilder for (line <- linesWithSeparators) { val len = line.length var index = 0 while (index < len && line.charAt(index) <= ' ') index += 1 buf append (if (index < len && line.charAt(index) == marginChar) line.substring(index + 1) else line) } buf.toString }