如何从列表中删除字符“ a”?

时间:2019-03-10 18:43:53

标签: kotlin

我有此代码:

fun main(args:Array<String>){

    var a = "eat, banana, one"
    var a1 = a.split(",").toMutableList()
    a1.sortBy { it.toCharArray().count { it == 'a' } }
    var a2 = a1.associateWith { word -> word.count { char -> char == 'a' } }

    a2.keys.filterNot { c -> "a".contains(c)}
   }

实际上,我想删除使用此行的单词中的“ a”: a2.keys.filterNot { c -> "a".contains(c)},但无效。

如何删除a2中的所有a?

非常感谢您!

2 个答案:

答案 0 :(得分:1)

要从密钥中删除所有a个字符,可以将它们替换为空字符串:

a2.mapKeys { it.key.replace("a", "")}

答案 1 :(得分:0)

您可以将键映射到新的映射,并用键中的空字符串替换a。然后,您需要使用新创建的地图作为结果:

fun main(args:Array<String>){
    val a = "eat, banana, one"
    val a1 = a.split(",").toMutableList()
    a1.sortBy { it.toCharArray().count { it == 'a' } }
    val a2 = a1.associateWith { word -> word.count { char -> char == 'a' } }

    val result = a2.mapKeys { it.key.replace("a", "")}
    println(result) // prints { one=0, et=1,  bnn=3}
}