Get first character in String in Kotlin
To get the first character in given string in Kotlin, you can use String.first()
function.
Call the first()
function on the given string str
.
str.first()
The function returns the first character in the string. But, if the string is empty, the function throws NoSuchElementException
.
Examples
Get first character in the string
In the following program, we take a string in str
and get the first character in this string using String.first()
function.
Kotlin Program
fun main(args: Array<String>) {
val str = "Hello World"
val firstChar = str.first()
println("First Character : $firstChar")
}
Output
First Character : H
Check if string is not empty before getting the first character
We can make a check if the string is not empty, and then get the first character. This way we can make sure that no Exception is thrown, and also we can look into doing something when the string is empty.
Kotlin Program
fun main(args: Array<String>) {
val str = "Hello World"
if (str.isNotEmpty()) {
val firstChar = str.first()
println("First Character : $firstChar")
} else {
println("String is empty.")
}
}
Output
First Character : H