In this tutorial, you shall learn how to get the first character in a given string in Kotlin, using String.first() function, with examples.

Kotlin – Get First Character in String

To get first character in string in Kotlin, we can use String.first() function. Call the first() function on the given string, and the function returns the first character in the string.

Syntax

If str is the given string, then the syntax of the function call to get the first character in this string is

str.first()
ADVERTISEMENT

Example

In the following program, we take a string in str, get the first character in the string, and print it to output.

Main.kt

fun main() {
    var str = "hello world"
    var firstChar = str.first()
    println("First Character : $firstChar")
}

Output

First Character : h

Conclusion

In this Kotlin Tutorial, we learned how to get the first character in a string using String.first() function.