Home » Kotlin Multiline string to single line

Kotlin Multiline string to single line

Kotlin Multiline string to single line

1. Overview

In this article, we will learn to convert Multiline string to a single line in Kotlin.

You can look into our Kotlin articles to know more about other topics.

Kotlin has two types of the string literal:

  • escaped strings that may contain escaped characters (For example: val s = "Hello, world!\n"). You can escape the characters in a conventional way, with a backslash (\).
  • raw or multiline strings that can contain newlines and arbitrary text and do not support backslash escaping.

2. Kotlin multiline string

A raw string is delimited by a triple quote ("""), contains no escaping and can contain newlines and any other characters.

For example, the following main method contains a raw string.

fun main() {
   val text = """
    |Tell me and I forget.
    |Teach me and I remember.
    |Involve me and I learn.
    |(Benjamin Franklin)
    """
    println(text)
    println("Done")
}

If you notice, the above code introduces additional leading whitespace characters.

    |Tell me and I forget.
    |Teach me and I remember.
    |Involve me and I learn.
    |(Benjamin Franklin)
Done

3. Convert Multiline string to a single line string

You can convert the multiline string to a single line string by using replace.

fun main() {
   val text = """
    >Tell me and I forget.
    >Teach me and I remember.
    >Involve me and I learn.
    >(Benjamin Franklin)
    """.trimMargin(">")
    println(text)
    println(text.replace("\n",""))
}

4. Conclusion

To sum up, we have learned to convert the multiline string to a single line string in Kotlin.

Leave a Reply

Your email address will not be published.