string - 带三引号的字符串位于带三引号的字符串内部

标签 string kotlin

我正在三重引号的字符串内部使用字符串:

fun main(args: Array<String>) {    
    val firstStr = """

    OLOLO
    """.trimIndent()

    val secondStr = """
    $firstStr
    new added text
    """.trimIndent()

    println("The firstStr is $firstStr")
    println("The secondStr is $secondStr")
}

并且我得到以下输出:
The firstStr is 
OLOLO
The secondStr is     
OLOLO
    new added text

而且我很困惑为什么缩进保留在最后一行(" new added text")...因为我期望trimIndent()方法必须修剪所有缩进(正如文档注释所说的那样)

Detects a common minimal indent of all the input lines, removes it from every line and also removes the first and the last lines if they are blank (notice difference blank vs empty).



同时,我可以使用带有默认参数(“|”)的trimMargin()削减此缩进:
fun main(args: Array<String>) {    
    val firstStr = """

    OLOLO
    """.trimIndent()

    val secondStr = """
    $firstStr
    |new added text
    """.trimMargin()

    println("The firstStr is $firstStr")
    println("The secondStr is $secondStr")
}

在这种情况下,我得到以下输出:
The firstStr is 
OLOLO
The secondStr is     
OLOLO
new added text

但是我不明白为什么trimIndent()不能缩小缩进...

最佳答案

trimIdent()的怪异似乎是由于开头有空行引起的。尽管前导空白行似乎毫无疑问地使所有内容显得毫无用处,但它对于前导制表符和空格在整个过程中的一致性还是有些挑剔。鉴于此,您可以在\n中包括换行符(println)作为解决方法。

fun main(args: Array<String>) {    

    val firstStr =
        """
            OLOLO
        """.trimIndent()

    val secondStr = 
        """
            $firstStr
            new added text
        """.trimIndent()

    println("The firstStr is \n$firstStr")
    println("The secondStr is \n$secondStr")

}

输出:
The firstStr is
OLOLO
The secondStr is
OLOLO
new added text

String.trimIndent(): String Detects a common minimal indent of all the input lines, removes it from every line and also removes the first and the last lines if they are blank (notice difference blank vs empty). Note that blank lines do not affect the detected indent level. In case if there are non-blank lines with no leading whitespace characters (no indent at all) then the common indent is 0, and therefore this function doesn't change the indentation.

Doesn't preserve the original line endings.



以下语句:“注意差异为空白还是为空”,尽管并不清楚它们的含义,但它可能是谜语的关键。绝对是奇怪的行为(可能是错误?)。

关于string - 带三引号的字符串位于带三引号的字符串内部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53229432/

相关文章:

date - 如何将月份或日期添加到当前/选择的日期 Kotlin

gradle - Gradle Kotlin DSL:配置任务: Unresolved reference

kotlin - Kotlin 如何调度调用运算符?

java - 字符串连接上的特定类型的哈希

php - 相同的字符串加盐代码给出不同的结果

c++ - 尝试计算一个像字符数组一样填充的字符串,但它只是计算字符串中的第一个字符

android - 如何禁用 LazyColumn 和 Column 中的滚动

generics - 在Kotlin中,如何定义具有上限的泛型类型的属性?

string - 如何从 Rust 中的字符串开头删除 "crop"个字符?

c - 首先添加什么 '\n' 或 '\0'