Find the Length of a String in Kotlin
To find the length of a string in Kotlin, use the length property. It returns an Int representing the number of characters in the string.
For example, "Kotlin".length returns 6. Spaces and other characters within the string are included in the length, while an empty string has a length of 0.
String length is commonly used when validating input, checking whether text is empty, limiting the size of a value, accessing characters by position, or deciding whether further string processing is required.
Kotlin String length Property 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 to a string literal or to a variable containing a string. The returned value can also be stored in a variable for later use.
The property name is length. In Kotlin, write str.length, without parentheses. Unlike Java code that commonly uses str.length() for a String, Kotlin exposes string length as a property.
val length: Int = str.length
Example 1 – Get the Length of a Kotlin String Variable
In this example, a string is assigned to str, and its length is read using the length property.
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
The value of str.length is 20, so the program prints 20.
Example 2 – Kotlin String Length for Text, Spaces, and an Empty String
You can access length directly on a string literal. The following example also shows how spaces and an empty string affect the result.
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" contains 5 characters. "hello world" has a length of 11 because the space between the two words is also counted. The empty string "" contains no characters, so its length is 0.
Example 3 – Store Kotlin String Length in an Int Variable
The value returned by length is an Int. You can therefore assign it to a variable and use that value in later expressions or conditions.
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
Kotlin length Property vs length() Method
Kotlin uses .length as a property for strings. You do not call it as a function, so there are no parentheses after length.
fun main() {
val text = "Kotlin"
val len = text.length
println(len)
}
Output
6
If you are moving from Java to Kotlin, this difference is easy to notice: Java strings commonly use length(), whereas Kotlin strings use length.
Does Kotlin String Length Count Spaces?
Yes. A space inside a string contributes to its length just like other characters. Leading and trailing spaces also contribute unless you remove them before checking the length.
fun main() {
val text = " Kotlin "
println(text.length)
println(text.trim().length)
}
Output
10
6
The original string contains two leading spaces, six letters, and two trailing spaces. Therefore, text.length returns 10. The trim() function returns a string with leading and trailing whitespace removed, so text.trim().length returns 6.
Check Whether a Kotlin String Has Length Zero
You can compare length with 0 when you specifically need the numeric length. When the intent is simply to test whether a string is empty, Kotlin also provides isEmpty().
fun main() {
val text = ""
println(text.length == 0)
println(text.isEmpty())
}
Output
true
true
An empty string has a length of zero. A string containing only spaces is different: its length is greater than zero. If you need to determine whether a string is empty or contains only whitespace, use isBlank().
fun main() {
val text = " "
println(text.length)
println(text.isEmpty())
println(text.isBlank())
}
Output
3
false
true
Get the Length of a Nullable String in Kotlin
A variable of type String? can contain either a string or null. Because null has no string length, access length safely with the safe-call operator ?..
fun main() {
val first: String? = "Kotlin"
val second: String? = null
println(first?.length)
println(second?.length)
}
Output
6
null
If the nullable variable contains a string, ?.length returns its length. If the variable is null, the expression returns null.
If your application needs a numeric default instead, combine the safe call with Kotlin’s Elvis operator ?:.
fun main() {
val text: String? = null
val len = text?.length ?: 0
println(len)
}
Output
0
Use Kotlin String Length in Validation Conditions
Because length returns an integer, it can be compared with a required minimum or maximum length. The following example checks whether a username contains at least five characters.
fun main() {
val username = "alex7"
if (username.length >= 5) {
println("Valid length")
} else {
println("Too short")
}
}
Output
Valid length
The same approach can be used for application-specific minimum-length and maximum-length checks.
Kotlin String Length Key Points
- Use
string.lengthto get the length of a Kotlin string. lengthis a property, not a method, so write.lengthrather than.length().- The returned length is an
Int. - An empty string has length
0. - Spaces within a string are included in its length.
- Use
trim()beforelengthwhen leading and trailing whitespace should not be included. - For a nullable
String?, use?.length, optionally with?:to provide a default value.
In this Kotlin Tutorial, we learned how to find String Length using String.length property with example Kotlin programs.
TutorialKart.com