kotlin: count函数
一,功能
count函数: 返回集合中的元素总数
或返回与给定条件匹配的元素数。
二,例子:
代码:
//处理按钮点击事件
binding.button1.setOnClickListener {
val numbers = listOf(1, -2, 3, -4, 5, -6)
val totalCount = numbers.count() //集合中的元素总数
val evenCount = numbers.count { it % 2 == 0 } //与给定条件匹配的元素数
println("总数量: ${totalCount}") // 打印 6
println("偶数数量: ${evenCount}") // 打印 3
val count = numbers.count { it > 1 && it < 7 }
println("大于1小于7之间的数字数量: ${count}") // 打印 2
}
运行结果:
三,例子:
代码:
//处理按钮点击事件
binding.button2.setOnClickListener {
val word = "Happy New Year"
val count = word.count()
val aCount = word.count {it == 'a'}
println("字符总数: ${count}") // 打印 14
println("字符a的数量: ${aCount}") // 打印 2
}
运行结果: