在這里和 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
希望這是有道理的......
uj5u.com熱心網友回復:
如果你想用連續空格作為分隔符來分割字串,你可以使用正則運算式。
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)
}
自己試試
uj5u.com熱心網友回復:
這里有一些錯誤,
- 您正在使用
forEach和洗掉索引來迭代陣列,這可能會導致IndexOutOfBoundError或其他一些模棱兩可的行為。
你可以在filter這里使用,
val a = listOf(" " ," " ," " ," " ,"1" ,"2" ,"3")
print( a.filter{it != " "} )
回傳
[1, 2, 3]
操場
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/355601.html
