val string = "5 kg rice 2 kg wheat 3 kg Soya"
Is there any higher-order function to count String "kg" in the above string?
val string = "5 kg rice 2 kg wheat 3 kg Soya"
Is there any higher-order function to count String "kg" in the above string?
fun main() {
val s = "5 kg rice 2 kg wheat 3 kg Soya"
val c = "\\bkg\\b".toRegex().findAll(s).count()
println(c)
}
This works:
println("5 kg rice 2 kg wheat 3 kg Soya".windowed(2, 1).count { it == "kg" })
But if you only want the occurrences of " kg ", you can use:
println("5 kg rice 2 kg wheat 3 kg Soyakg".windowed(4, 1).count { it == " kg " })
I believe it could work also:
println("5 kg rice 2 kg wheat 3 kg Soya".splitToSequence(" kg ").count() - 1)
As I said before the way you split the string or check the windowed string will depend on what kind of occurrence you consider valid.
The easiest way is:
val count = s.split("kg").size - 1
After you split your string by using split extension function, size minus one gives you the occurence count.
you can test this solution on Kotlin Playground: https://pl.kotl.in/y6Sciwgzk
There seems to be no function from the standard library that counts substrings. But you can easily write an extension function that uses the indexOf(element, startIndex) function:
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
}