Kotlin.Count 字符串的出现次数。

问题描述 投票:0回答:1
val string = "5 kg rice 2 kg wheat 3 kg Soya"

有没有高阶函数来计算上面字符串中的 "kg"?

kotlin kotlin-android-extensions
1个回答
3
投票

标准库中似乎没有计算子串的函数。但你可以很容易地写一个扩展函数,使用的是 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
}

3
投票

这样就可以了。

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)

就像我之前说的,你分割字符串或者检查窗口字符串的方式 将取决于你认为哪种类型的出现是有效的。


3
投票
fun main() {
    val s = "5 kg rice 2 kg wheat 3 kg Soya"
    val c = "\\bkg\\b".toRegex().findAll(s).count()
    println(c)
}

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.