如何計算特定字符在 Kotlin 字串中出現的次數?
從查看https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-string/沒有內置任何東西,每次都需要撰寫回圈(或可能擁有擴展功能),但也許我錯過了實作這一目標的更好方法是什么?
uj5u.com熱心網友回復:
使用 filter {} 函式很容易
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
從節省計算機資源的角度來看,計數決策(第二種方法)更正確。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/339709.html
標籤:科特林
