这里有一些String https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-string/index.html您可以使用的扩展功能
任何字符的出现
随着fold https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.text/fold.html扩展功能:
val string1 = "Hello"
val string2 = "Hello world Hello"
print(
string2.fold(0) {
sum: Int, c: Char ->
if (string1.contains(c))
sum + 1
else
sum
}
)
或者甚至更短sumBy https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.text/sum-by.html:
string2.sumBy {
if (string1.contains(it))
1
else
0
}
或者甚至更短:
string2.count { string1.contains(it) }
或者最短:
string2.count { it in string1 }
每个字符单独出现的次数
With forEach https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.text/for-each.html and a MutableMap https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-mutable-map/index.html:
val charsMap = mutableMapOf<Char, Int>()
string2.forEach{
charsMap[it] = charsMap.getOrDefault(it, 0) + 1
}
print(charsMap)
整体的发生string1
随着windowed https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.text/windowed.html扩展功能:
string2.windowed(string1.length){
if (it.equals(string1))
1
else
0
}.sum()
您可以浏览更多String
中的扩展函数String存储库页面 https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-string/index.html