Scala多行字符串

在Scala中可以用"""的方式創(chuàng)建多行字符串,eg.

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

但是這種方式有個(gè)問(wèn)題,就是每行的開(kāi)頭可能會(huì)有空格;如何消除空格,可以在多行字符串的結(jié)尾添加stripMargin方法,并且在第二行開(kāi)始的每一行前面添加|,eg.

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

輸出如下:

This is
my first time
to learn Scala

如果不想使用|,也可以使用其他任意字符,eg.

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("#"),這個(gè)會(huì)出現(xiàn)Cannot resolve reference stripMargin with such signature;
Scala的多行,其實(shí)在每個(gè)換行的字符串之間生成\n的換行符,可以將替換掉,eg.

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

輸出如下:

This is my first time to learn Scala

這個(gè)replace需要注意的是,在編輯器中需要使用replaceAll("\r\n", " "),但是在scala的REPL中只需要使用replaceAll("\n", " ");原因如下:

Your Idea making the newline marker the standard Windows \r\n, so you've got "abcd\r\nefg". The regex is turning it into "abcd\refg" and Idea console is treaing the \r slightly differently from how the windows shell does. The REPL is just using \n as the new line marker so it works as expected.

Solution 1: change Idea to just use \n newlines.

Solution 2: don't use triple quoted strings when you need to control newlines, use single quotes and explicit \n characters.

Solution 3: use a more sophisticated regex to replace \r\n, \n, or \r

Scala多行字符串的另外一個(gè)功能是,單引號(hào)和雙引號(hào)無(wú)需進(jìn)行轉(zhuǎn)義,eg.

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

輸出如下:

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

stripMargin函數(shù)在StringLike.scala源碼中默認(rèn)使用了|這個(gè)字符串;

/** 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
  }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容