pixel
pixel

Reputation: 26453

Trim all newlines from String in Kotlin - idiomatic way

Is there a built-in/standard lib method to trim all new lines from a string, not only from the beginning or the end?

Upvotes: 4

Views: 9053

Answers (2)

SerjantArbuz
SerjantArbuz

Reputation: 1244

In case if you need to remove all empty lines (without any symbols, like: \n\n) you could use this extension:

fun String.trimEmptyLines() = trim().replace("\n+".toRegex(), replacement = "\n")

Example input:

1
2

3


4

Output:

1
2
3
4

Upvotes: 1

Joffrey
Joffrey

Reputation: 37710

There is no special stdlib function to my knowledge that specifically removes new lines, but you could simply use text.replace("\n", "") if you're only interested in removing \n characters.

If you want to cover more cases, like more line ending characters/sequences, or whitespace after new lines, you can also use a regex. For instance text.replace(Regex("""(\r\n)|\n"""), ""), but that may be overkill in many cases.

Yet another option is to get the lines themselves independently, and then join them back together with an empty separator:

text.lines().joinToString("")

Upvotes: 11

Related Questions