Kotlin 将回车 return 添加到多行字符串中

Kotlin add carriage return into multiline string

在 Kotlin 中,当我像这样构建多行字符串时:

value expected = """
                |digraph Test {
                |${'\t'}Empty1;
                |${'\t'}Empty2;
                |}
                |""".trimMargin()

当我通过以下方式输出时,我看到字符串缺少回车符 return 字符(ASCII 代码 13):

println("Expected bytes")
println(expected.toByteArray().contentToString())

输出:

Expected bytes
[100, 105, 103, 114, 97, 112, 104, 32, 84, 101, 115, 116, 32, 123, 10, 9, 69, 109, 112, 116, 121, 49, 59, 10, 9, 69, 109, 112, 116, 121, 50, 59, 10, 125, 10]

当我尝试进行单元测试的某些代码通过 PrintWriter 构建相同的字符串时,它通过 lineSeparator 属性:

描绘行
/* 
 * Line separator string.  This is the value of the line.separator
 * property at the moment that the stream was created.
 */

所以我最终得到一个字符串,在输出中看起来相同,但由不同的字节组成,因此不相等:

Actual bytes
[100, 105, 103, 114, 97, 112, 104, 32, 84, 101, 115, 116, 32, 123, 13, 10, 9, 69, 109, 112, 116, 121, 49, 59, 13, 10, 9, 69, 109, 112, 116, 121, 50, 59, 13, 10, 125, 13, 10]

在字符串声明期间,有没有比将我的多行字符串拆分成串联的小字符串更好的方法来解决这个问题,每个小字符串都可以以char(13)作为后缀?

或者,我想做类似的事情:

value expected = """
                |digraph Test {
                |${'\t'}Empty1;
                |${'\t'}Empty2;
                |}
                |""".trimMargin().useLineSeparator(System.getProperty("line.separator"))

.replaceAll()之类的。

是否存在任何标准方法,或者我应该向 String 添加自己的扩展函数?

Kotlin 多行字符串总是被编译成使用 \n 作为行分隔符的字符串文字。如果你需要有 platform-dependent 行分隔符,你可以做 replace("\n", System.getProperty("line.separator")).

从 Kotlin 1.2 开始,没有标准库方法,所以如果您经常使用它,您应该定义自己的扩展函数。

这成功了。

    System.lineSeparator()