Different ways to find the length of a string in Kotlin

Introduction :

In this tutorial, we will learn different ways to find the length of a string. Actually you can use string property length that gives the length of a string in Kotlin. I am showing you three different ways. But I would recommend you to use length.

Method 1: Using length :

length property of Kotlin string returns the length of a string. It returns one Int value. Example :

fun main() {
    val testStr = "Hello, World"
    println(testStr.length)
}

It will print 12. This is the easiest and recommended approach.

Method 2: By converting it to a character array :

We can use toCharArray method to convert one string to a character array. count property of an array returns the character count :

fun main() {
    val testStr = "Hello, World"
    println(testStr.toCharArray().count())
}

It will also print 12.

Method 3: Getting the index of the last character :

last() method of the String class returns the last character. And indexOfLast method takes one predicate and returns the last character that matches the predicate. If it doesn’t find that character, it returns -1.

So, we can get the last character of a string and get its index in the string. But index starts from 0. Adding 1 to the index of the last character will return the length of the string.

fun main() {
    val testStr = "Hello, World"

    println(testStr.indexOfLast { e -> e == testStr.last()} + 1)
}

Here, the predicate checks if the character is equal to the last character of the string or not. Like the above examples, it will also print 12.

Example of all :

fun main() {
    val str = "The quick brown fox jumps over the lazy dog"

    println(str.length)
    println(str.toCharArray().count())
    println(str.indexOfLast { e -> e == str.last()} + 1)
}

Output :

43
43
43

kotlin find length of a string

Similar tutorials :