In this tutorial, you shall learn how to get a character at specific index in given string in Kotlin, using String.get() function, with examples.
Kotlin Get character at specific index in string
To get character at specific index of String in Kotlin, use String.get() method.
Given a string str1
, and if we would like to get the character at index index
in the string str1
, call get() method on string str1
and pass the index index
as argument to the method as shown below.
str1.get(index)
get() method returns the character at index
.
Examples
1 Get character at index2 in string abcd
In this example, we will take a string in str1
, and get the character at index 2
.
Kotlin Program
fun main(args: Array<String>) { val str1 = "abcd" val index = 2 val ch = str1.get(index) println("The character at index 2 is : " + ch) }
Output
The character at index 2 is : c
2 Index out of bounds for string
If the specified index is out of bounds for the given string, the get() method throws java.lang.StringIndexOutOfBoundsException.
Kotlin Program
fun main(args: Array<String>) { val str1 = "abcd" val index = 8 val ch = str1.get(index) println("The character at index 2 is : " + ch) }
Output
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 8 at java.base/java.lang.StringLatin1.charAt(StringLatin1.java:44) at java.base/java.lang.String.charAt(String.java:692) at KotlinExampleKt.main(KotlinExample.kt:4)
Conclusion
In this Kotlin Tutorial, we learned how to get the character at specific index in given string using String.get() method, with the help of Kotlin example programs.