Finding the length of a string

Kotlin:
Finding the length of a string

How to:

fun main() {
    val greeting = "Hello, World!"
    println(greeting.length)  // prints 13
}

Output:

13

Deep Dive

In the early days of computing, strings were handled differently, often with null-terminated arrays in languages like C. Kotlin, as a modern language, provides a built-in length property for String objects.

Alternatives? Well, you could loop through a string and count characters—but why reinvent the wheel? Kotlin’s length is efficient and simple.

Under the hood, length returns the count of UTF-16 code units in the string. This means that for most text (like English), the number of code units matches the number of characters. However, for characters outside the Basic Multilingual Plane (BMP), which are represented by two code units (a surrogate pair), the length property might not align with the number of Unicode code points.

See Also