我有此代码:
fun main(args:Array<String>){
var a = "banana, eat, one"
var a1 = a1.split("a").toMutableList()
a1.sortBy { it.toCharArray().count { it == 'a' } }
}
此代码允许我按a的顺序对列表a1进行排序,但我希望每个单词(香蕉,进餐,一个)的a数均具有。我想创建一个HashMap这样的东西: (香蕉,3) (吃,1) (一,0)
但是我不知道是否有允许我执行此操作的功能?
你能帮我吗?
谢谢。
答案 0 :(得分:1)
您现有的代码未编译,但我认为您打算在第二行中使用a
并在,
上拆分。如果是这样,您可以使用associateWith
创建一个Map
,其中键是您的单词,值是每个单词中'a'
的计数:
val a = "banana, eat, one"
val a1 = a.split(", ").toMutableList()
val a2 = a1.associateWith { word -> word.count { char -> char == 'a' } }
println(a2) // {banana=3, eat=1, one=0}
答案 1 :(得分:0)
fun main(args:Array<String>){
val input = "banana, eat, one"
// split the words
val split = input.split(",")
val map = HashMap<String, Int>()
for (word in split) {
var countA = 0
// count the character 'a' per word
for (character in word) {
if (character == 'a' || character == 'A') {
countA++
}
}
map[word] = countA
}
println(map)
}
答案 2 :(得分:-2)
"banana, eat, one".split(",").associateBy({ it }, { it.count { it.toLowerCase() == 'a' } })