Kotlin String Length

To find the length of string in Kotlin language, you can use String.length property. String.length property returns the number of characters in the string.

You may need to find the string length during scenarios like: string validation; check if string is empty; check if string is exceeding an allowed length; etc.

In this tutorial, we will learn how to find the length of a string, with Kotlin example programs.

Syntax

The syntax of String length property is

String.length

Following is a quick example to use string length property.

"hello world".length //11

"tutorialkart".lentgh //12

var s = "hello"
var len = s.length //5

You can apply the length property directly on a string constant or a string variable. And you can store the result of String.length in a variable.

Example 1 – Kotlin String Length

In this example, we will take a string constant in a val, and find its length using length property. We shall directly print the length.

Kotlin Program – example.kt

/**
 * Kotlin String length
 */
fun main(args: Array<String>) {
    val str = "www.tutorialkart.com"
    print(str.length)
}

Run the Kotlin program.

Output

20

Since there are twenty characters in the string, str.length returned 20.

Example 2 – Length of Kotlin String – Different Scenarios

You can apply the length property directly on the string.

Kotlin Program – example.kt

/**
 * Kotlin String length
 */
fun main(args: Array<String>) {
    println("hello".length)
    println("hello world".length)
    println("".length)
}

Run the Kotlin program and you shall get the following output.

Output

5
11
0

"hello" has 5 characters. "hello world" has 11 characters and of course, empty string has zero characters.

Example 3 – Store the String Length

In this example, we shall find the string length and store it in a variable.

Kotlin Program – example.kt

/**
 * Kotlin String length
 */
fun main(args: Array<String>) {
    val str = "www.tutorialkart.com"
    val len = str.length
    print(len)
}

Run the above Kotlin example program.

Output

20

Conclusion

In this Kotlin Tutorial, we learned how to find String Length using String.length property with example Kotlin programs.