第一章 Strings(二):创建多行字符串

Problem

    你想要创建一个多行的字符串在你的Scala程序中。

Solution

    在Scala中,你可以通过吧字符串包在三个双引号中来创建多行字符串。

scala> val foo = """This is 
     |   a multiline
     |   String"""
foo: String = 
This is 
  a multiline
  String

    你会发现代码格式上的缩进会导致缩进会导致字符串打印后出现如下的情况,缩紧的空格也带到了字符串中。

This is 
  a multiline
  String

    我们有两种方法来解决这个问题,第一个是不用缩进,每行都左对齐,但是这样代码就非常的不美观了。

scala> val foo = """This is
     | a multiline
     | String"""
foo: String = 
This is
a multiline
String

    我们还可以对字符串每行添加一个'|'符号,并调用字符串的stripeMargin方法来解决这个问题:

scala> val speech = """Four score and 
     |   |seven years age""".stripMargin
speech: String = 
Four score and 
seven years age

    如果你不想使用|,你还可以任意使用其他字符,比如'#':

scala> val speech = """Four score and 
     |   #seven years age""".stripMargin('#')
speech: String = 
Four score and 
seven years age

    我们看到多行字符串都是按输入格式存储的,如果我们想要让这个多行字符串按一行存储,我们可以使用stripMargin.replaceAll("\n", " "),来把每行末位隐藏的\n换行转化为" ":

scala> val speech = """Four score and
     | |seven years ago
     | |our fathers""".stripMargin.replaceAll("\n", " ")
speech: String = Four score and seven years ago our fathers

    使用多行字符串的另外一个好处是,你可以在不使用转义字符的情况下来使用单引号和双引号。

scala> val s = """This is known as a
     | |"multiline" string
     | |or 'heredoc' syntax.""".stripMargin.replaceAll("\n", " ")
s: String = This is known as a "multiline" string or 'heredoc' syntax.


你可能感兴趣的:(scala,multiline,多行字符串,stripMargin)