Kotlin:多行字符串中的行继续?

问题描述 投票:0回答:2
val myQuestion = """
I am creating a multiline string containing paragraphs of text.  The text will wrap when put into a TextView.  

But as you can see, when defining the text in the editor, if I want to avoid newlines mid-paragraph, I need to write really long lines that require a lot of horizontal scrolling.

Is there some way that I can have line breaks in the editor that don't appear in the actual value of the string?
"""
kotlin multiline
2个回答
10
投票

受到如何通过执行

$
在多行字符串中添加
${"$"}
(否则无法做到)的启发,我想到了这种在多行字符串文字中添加换行符的方法,而不是在字符串中添加换行符价值本身。

val myQuestion = """
    I am creating a multiline string containing paragraphs of text.  ${""
    }The text will wrap when put into a TextView.  

    But as you can see, when defining the text in the editor, ${""
    }if I want to avoid newlines mid-paragraph, I need to write ${""
    }really long lines that require a lot of horizontal scrolling.

    Is there some way that I can have line breaks in the editor ${""
    }that don't appear in the actual value of the string?
""".trimIndent()

(缩进和

trimIndent
只是为了让它看起来漂亮。它们不是必需的。)

基本上,我正在利用这样一个事实:您可以在

${ ... }
中放置任意空格,那么在那里放置换行符怎么样?不过
${ ... }
中仍然必须有一个表达式,因此您必须编写
""
nothing 附加到字符串中。


5
投票

另一种方法是将 single-newline 视为“仅编辑器”换行符,该换行符将被删除。 如果您确实想要一个单换行符,请放置一个双换行符。 如果你想要双倍,就放三倍,依此类推:

val myQuestion = """
    I am creating a multiline string containing paragraphs of text.  
    The text will wrap when put into a TextView.  


    But as you can see, when defining the text in the editor, 
    if I want to avoid newlines mid-paragraph, I need to write 
    really long lines that require a lot of horizontal scrolling.


    Is there some way that I can have line breaks in the editor 
    that don't appear in the actual value of the string?
""".trimIndent().replace(Regex("(\n*)\n"), "$1")

这类似于 Markdown 的方法 - 它忽略单独的换行符(除非前一行以 2 个或更多空格结尾 - 我觉得这很令人困惑)。

© www.soinside.com 2019 - 2024. All rights reserved.