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

Pet*_*ter 5 multiline kotlin

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?
"""
Run Code Online (Sandbox Code Playgroud)

Swe*_*per 9

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

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()
Run Code Online (Sandbox Code Playgroud)

(缩进 和trimIndent只是为了让它看起来漂亮。它们不是这个工作所必需的。)

基本上,我正在利用这样一个事实,即您可以在 中放置任意空格${ ... },那么在那里放置换行符怎么样?但仍然必须有一个表达式${ ... },因此您必须编写不向字符串""添加任何内容的内容。


Pet*_*ter 4

另一种方法是将单个换行符视为“仅限编辑器”换行符,并将其删除。如果您确实想要一个单换行符,请放置一个双换行符。如果您想要双倍,请输入三倍,依此类推:

val INFO_TEXT = """
    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")
Run Code Online (Sandbox Code Playgroud)

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