You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Kotlin中count方法无法统计数组字符串元素数量问题求助

问题解决:Kotlin count方法类型不匹配错误

错误原因

你调用sentArr.count(x)时出错,是因为Kotlin集合的count方法接受的参数是一个布尔判断的lambda表达式((T) -> Boolean),而你直接传入了字符串x,类型不匹配导致报错。

修正方案

基础修正:正确统计元素出现次数

把count(x)改成count { it == x },用lambda判断当前元素是否等于x:

fun main() {
    var sentence = "Bob hit a ball, the hit BALL flew far after it was hit."
    var sentArr = sentence.split(" ")
    var bannedWords = arrayOf("ball")
    
    for(x in sentArr){
        println(sentArr.count { it == x })
    }
}

优化处理:忽略标点与大小写,排除禁用词

原代码里的split(" ")会保留标点(比如ball,),且大小写敏感(ball和BALL会被当成不同单词),如果需要更准确的统计,可以先预处理字符串:

fun main() {
    val sentence = "Bob hit a ball, the hit BALL flew far after it was hit."
    // 预处理:去掉标点、转小写,再分割成单词
    val cleanWords = sentence.lowercase()
        .replace(Regex("[^a-z\\s]"), "")
        .split(" ")
        .filter { it.isNotEmpty() } // 过滤空字符串
    val bannedWords = setOf("ball") // 用Set查询更快
    
    // 统计每个非禁用词的出现次数
    val wordCount = mutableMapOf<String, Int>()
    for (word in cleanWords) {
        if (word !in bannedWords) {
            wordCount[word] = wordCount.getOrDefault(word, 0) + 1
        }
    }
    
    // 打印结果
    wordCount.forEach { (word, count) ->
        println("$word: $count")
    }
}

这段代码做了这些优化:

  • 把字符串转成小写,消除大小写差异
  • 用正则去掉所有非字母和空格的字符,清理标点
  • 用Set存储禁用词,查询效率更高
  • 用Map统计次数,避免重复遍历集合,性能更好

内容的提问来源于stack exchange,提问作者86BuickRegal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 02:57:28