0
0
KotlinHow-ToBeginner · 3 min read

How to Find Length of String in Kotlin: Simple Guide

In Kotlin, you can find the length of a string using the length property. For example, val len = myString.length gives the number of characters in myString.
📐

Syntax

To get the length of a string in Kotlin, use the length property directly on the string variable.

  • stringVariable.length: Returns the number of characters in the string.
kotlin
val myString = "Hello"
val length = myString.length
💻

Example

This example shows how to find and print the length of a string in Kotlin.

kotlin
fun main() {
    val greeting = "Hello, Kotlin!"
    val length = greeting.length
    println("The length of the string is: $length")
}
Output
The length of the string is: 14
⚠️

Common Pitfalls

One common mistake is trying to call length() as a function like in some other languages. In Kotlin, length is a property, not a function, so you should not use parentheses.

Also, be careful with null strings; accessing length on a null string will cause an error.

kotlin
fun main() {
    val text: String? = null
    // Wrong: val len = text.length() // This causes error
    // Correct with safe call:
    val len = text?.length ?: 0
    println("Length is: $len")
}
Output
Length is: 0
📊

Quick Reference

Summary tips for finding string length in Kotlin:

  • Use string.length to get the number of characters.
  • Do not use parentheses after length.
  • Use safe calls (?.) if the string can be null.

Key Takeaways

Use the length property to get the number of characters in a Kotlin string.
Do not add parentheses after length because it is a property, not a function.
Use safe calls (?.length) to avoid errors when strings can be null.
The length counts all characters including spaces and punctuation.
Remember that length returns an Int representing the string size.