Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Trouble removing whitespaces from string array

New to asking questions here and to Kotlin so,

I’m making a simple command parser for a command line app. I handle input but splitting the string at whitespaces but it could possibly result in "empty array indexes". This is the code I currently have for trying to remove it but, the console will never print "Found Whitespace", so I’m not quite sure how to go about this.

var input = readLine()?.trim()?.split(" ")

        input = input?.toMutableList()
        println(input)
        if (input != null) {
            for(i in input){
                println("Checked")
                if(i == " "){
                    println("Found Whitespace")
                    if (input != null) {
                        input.removeAt(input.indexOf(i))
                    }
                }
            }
        }
        println(input)

Here’s the console for a command that repeats the first number by the second

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

repeat   5  5 // command
[repeat, , , 5, , 5]  //what the array looks like before whitespace removal
Checked
Checked
Checked
Checked
Checked
Checked
[repeat, , , 5, , 5] //what the array looks like after whitespace removal

Hopefully this makes sense…

>Solution :

If you want to split the string with consecutive spaces as a delimiter, you can use a regex for that.

val input = readLine()
if(input != null) {
    val words = input.trim().split(Regex(" +")) // here '+' is used to capture one or more consecutive occurrences of " "
    println(words)
}

Try it yourself

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading