【发布时间】: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