val string = "5 kg rice 2 kg wheat 3 kg Soya"是否有更高阶的函数来计算上述字符串中的字符串"kg“?
发布于 2020-05-12 20:51:51
fun main() {
val s = "5 kg rice 2 kg wheat 3 kg Soya"
val c = "\\bkg\\b".toRegex().findAll(s).count()
println(c)
}发布于 2020-05-12 19:46:33
这是可行的:
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)正如我之前所说的,拆分字符串或检查窗口字符串的方式将取决于您认为有效的发生类型。
发布于 2020-05-12 19:04:41
标准库中似乎没有计算子字符串的函数。但是您可以很容易地编写一个使用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
}https://stackoverflow.com/questions/61749642
复制相似问题