首页 > 解决方案 > 无法从字符串数组中删除空格

问题描述

在这里和 Kotlin 提问的新手,

我正在为命令行应用程序制作一个简单的命令解析器。我处理输入,但在空格处拆分字符串,但它可能会导致“空数组索引”。这是我目前尝试删除它的代码,但是控制台永远不会打印“找到空白”,所以我不太确定如何去做。

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)

这是一个命令的控制台,该命令将第一个数字重复第二个数字

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

希望这是有道理的......

标签: arrayskotlinwhitespaceremoving-whitespace

解决方案


如果你想用连续的空格作为分隔符分割字符串,你可以使用正则表达式。

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)
}

自己试试


推荐阅读