val string = "5 kg rice 2 kg wheat 3 kg Soya"
有没有高阶函数来计算上面字符串中的 "kg"?
标准库中似乎没有计算子串的函数。但你可以很容易地写一个扩展函数,使用的是 indexOf(element, startIndex)
功能。
fun main() {
val string = "5 kg rice 2 kg wheat 3 kg Soya"
println(string.count("kg"))
}
fun String.count(element: String): Int {
var count = 0
// Check if the string contains the element at all
var lastIndex = indexOf(element, 0)
while (lastIndex > 0) {
count += 1
// Find the next occurence
lastIndex = indexOf(element, lastIndex + 1)
}
return count
}
这样就可以了。
println("5 kg rice 2 kg wheat 3 kg Soya".windowed(2, 1).count { it == "kg" })
但如果你只想要 "kg "的出现,你可以用..:
println("5 kg rice 2 kg wheat 3 kg Soyakg".windowed(4, 1).count { it == " kg " })
我相信这也可以。
println("5 kg rice 2 kg wheat 3 kg Soya".splitToSequence(" kg ").count() - 1)
就像我之前说的,你分割字符串或者检查窗口字符串的方式 将取决于你认为哪种类型的出现是有效的。
fun main() {
val s = "5 kg rice 2 kg wheat 3 kg Soya"
val c = "\\bkg\\b".toRegex().findAll(s).count()
println(c)
}