Kotlin String.count()

Kotlin String.count() Tutorial

The String.count() function in Kotlin is used to find the length of this string. If a predicate is given as argument, then it returns the number of characters matching the given predicate.

In this tutorial, we’ll explore the syntax of the String.count() function and provide examples of its usage in Kotlin strings.

Syntax

The syntax of the String.count() function is as follows:

fun CharSequence.count(
    predicate: (Char) -> Boolean
): Int

The count() function takes a single parameter:

ParameterDescription
predicate[Optional]
A lambda function that defines the condition for counting. The lambda function should return true for the characters to be included in the count.
Parameters of String.count() function

Examples for String.count() function

1. Getting the length of the String using count()

In this example, we’ll take a string in myString. We shall use count() to find the length of the string value in myString, and print the length to output.

Kotlin Program

fun main() {
    val myString = "Hello World!"

    // Using count()
    val count = myString.count()

    println("String length:\n$count")
}

Output

String length:
12

2. Counting Specific Characters

We shall take a predicate function that returns true if the character is l. When this predicate function is passed as argument to the count() function, then it returns the number of occurrences of character l in the string.

Kotlin Program

fun main() {
    val myString = "Hello World!"

    // Using count()
    val count = myString.count{ it == 'l' }

    println("Occurrences of 'l' :\n$count")
}

Output

Occurrences of 'l' :
3

Since there are three occurrences of l in the given string Hello World!, the count() function returns 3.

Summary

In this tutorial, we’ve covered the count() function in Kotlin strings, its syntax, and how to use it to count the occurrences of specific characters based on a provided predicate. This function is versatile and allows you to tailor the counting criteria using a lambda function.