如何计算 Kotlin 中特定字符在字符串中出现的次数?
查看https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-string/没有任何内置的东西,每次都需要编写循环(或者可能拥有扩展函数),但也许我错过了一种更好的方法来实现这一点?
最佳答案
使用过滤器 {} 功能轻松实现
val str = "123 123 333"
val countOfSymbol = str
.filter { it == '3' } // 3 is your specific character
.length
println(countOfSymbol) // output 5
另一种方法
val countOfSymbol = str.count { it == '3'} // 3 is your specific character
println(countOfSymbol) // output 5
从节省计算机资源的角度来看,计数决策(第二种方法)更为正确。
关于kotlin - 计算特定字符在字符串中出现的次数 - Kotlin,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69742497/