How to remove newlines from a string Kotlin

2 Answers

0 votes
fun removeNewlines(s: String): String =
    s.replace("\n", "").replace("\r", "")

fun main() {
    val s = "c# \n  c c++  \n java python\ngo\n";
    val result = removeNewlines(s)
    
    println(result)
}



/*
run:

c#   c c++   java pythongo

*/

 



answered Feb 22 by avibootz
0 votes
fun removeNewlines(s: String): String =
    s.replace("\\s+".toRegex(), " ").trim()

fun main() {
    val s = "c# \n  c c++  \n java python\ngo\n";
    val result = removeNewlines(s)
    
    println(result) // result without extra spaces
}



/*
run:

c# c c++ java python go

*/

 



answered Feb 22 by avibootz
...