【问题标题】:Kotlin add carriage return into multiline stringKotlin 将回车添加到多行字符串中
【发布时间】:2018-08-02 16:06:17
【问题描述】:

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

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

当我通过以下方式输出字符串时,我看到字符串缺少回车符(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 中?

【问题讨论】:

  • 你在什么操作系统上运行?
  • 视窗。一定是的。
  • 随便.replace("\n", "\r\n")
  • 阅读en.wikipedia.org/wiki/Newline可能会更好,尤其是第一个表格部分。

标签: kotlin multiline multilinestring


【解决方案1】:

Kotlin 多行字符串总是被编译成使用 \n 作为行分隔符的字符串文字。如果需要平台相关的行分隔符,可以replace("\n", System.getProperty("line.separator"))

从 Kotlin 1.2 开始,没有用于此的标准库方法,因此如果您经常使用此功能,则应定义自己的扩展函数。

【讨论】:

    【解决方案2】:

    这成功了。

        System.lineSeparator()
    

    【讨论】:

      猜你喜欢
      • 2011-04-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多