arrays - 无法从字符串数组中删除空格
问题描述
在这里和 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
希望这是有道理的......
解决方案
如果你想用连续的空格作为分隔符分割字符串,你可以使用正则表达式。
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)
}
推荐阅读
- json - 如何在 Flutter 中集成 MikroTik API?
- python - 在模型中编写查询
- java - 如何解决 dio https 状态 401 错误?
- python - 从第一个键中删除最后一个值
- strapi - “找不到模型用户权限。”
- javascript - 如何在反应项目中处理一个地方的axios错误?
- javascript - 为什么符号计算的属性名称不能在 VUE 数据中使用
- asynchronous - 发送 API 响应后使用 Response.OnCompleted 执行工作(.NET Core 3.1)
- angular - 如何从Angular中的验证器错误中获取价值
- authentication - 向具有 LDAP 身份验证的用户授予授权