Search code examples
kotlinkotlin-multiplatform

how to read mutliple lines of string into one variable using readln() in kotlin?


example:

a variable

val str = readln().replace("[^A-Za-z0-9 ] \\s+".toRegex(),"").trim()

should read multiple lines of input value, input value will be like this

 heading
----------
topic1

topic2

or like this

heading
-------
a) topic1

b) topic2

input may contain special characters or tabs or spaces we need to remove them also


Solution

  • I don't know what your Regex is trying to do, but that's not really your question.

    How do you know when the user has finished their input - a special word or an empty line?

    Assuming an empty line, here's how you can get all the content

    println("Enter something:")
    var lines = ""
    do {
        val line = readLine()
        lines += "${clean(line)}\n"
    } while (!line.isNullOrBlank())
    println("User input:\n$lines")
    
    private fun clean(line: String?): String? {
        return line?.replace("[^A-Za-z0-9 ] \\s+".toRegex(),"")?.trim()
    }