Skip to content
DeveloperMemos

Removing Empty Lines from a String in Kotlin

Kotlin, String, Regular Expression1 min read

Let's say we have the following string with empty lines in it:

1val myString = """
2Hello,
3
4this is a
5
6string with
7
8
9empty lines.
10"""

In order to remove the empty lines from this string, we can use the following function:

1fun removeEmptyLines(myString: String): String {
2 val regex = Regex("\n\\s*\n")
3 return myString.replace(regex, "")
4}

This function creates a Regex object with the regular expression "\n\s*\n", which matches empty lines in the string. It then uses the replace method to replace all the empty lines with an empty string.

To use this function, we can simply call it and pass our string as an argument:

1val result = removeEmptyLines(myString)

The result variable will now contain the modified string with all the empty lines removed. Here is the resulting string:

1Hello,this is astring withempty lines.

As you can see, the empty lines have been successfully removed from the string. I hope this example has been helpful in showing you how to remove empty lines from a string in Kotlin.