Home > front end >  Trouble removing whitespaces from string array
Trouble removing whitespaces from string array

Time:11-10

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

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...

CodePudding user response:

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

CodePudding user response:

There are some mistakes here,

  • you are iterating array using forEach and removing indices , this may cause IndexOutOfBoundError or some other some ambiguous behavior.

You can just use filter here,

val a = listOf(" " ," " ," " ," " ,"1" ,"2" ,"3")
print( a.filter{it != " "} )

returns

[1, 2, 3]

playground

  • Related