1. Introduction

The String is one of the basic variable types in Kotlin, and operating on a plain string is a pretty common use case. In this tutorial, we’ll learn how to easily get a character by index from a String.

2. Using Indexing

A String is a sequence of characters. We can use indexing operations to get specific characters from a string. The indexing starts from zero, like in Java, so the first character is at index zero. To indicate a specific character, we should place the index of this character between square brackets:

val string = "Baeldung"
assertEquals('l', string[3])

3. Using get() 

The String class has a function get(), which returns the character of a given string at the specified index. Just like the previous example, the indexing starts from zero:

val string = "Baeldung"
assertEquals('l', string.get(3))

As in Java, if the specified index is out of bounds for the given string, the get() method throws StringIndexOutOfBoundsException.

4. Using first(), last(), and single()

In Kotlin, there are few convenient functions for operating on strings. If we want to retrieve only the first letter of the string, we can use the first() function:

val string = "Baeldung"
assertEquals('B', string.first())

In a similar way, we can use the last() function to retrieve the last character of the string:

val string = "Baeldung"
assertEquals('g', string.last())

Another useful function is single(). The single() function returns the single character of the sequence or throws an exception if the character sequence is empty or contains more than one character:

val string = "A"
assertEquals('A', string.single())

5. Using CharArray

The next way to obtain a single character from the string involves first converting it to CharArray using the built-in function toCharArray(). Then, we can have access to the char by the index of the array. Let’s see an example:

val string = "Baeldung"
val toCharArray = string.toCharArray()
assertEquals('l', toCharArray[3])

6. Using subSequence() 

Another way to retrieve a single character from a string is using a subsequence of the string itself. First, we get a substring from our string and then convert it to a single character. Let’s see it in action:

val string = "Baeldung"
val substring = string.subSequence(3, 4).single()
assertEquals('l', substring)

7. Conclusion

In this article, we’ve seen the most common ways to get a character from a string in Kotlin. Using Kotlin’s built-in functions allows our code to be cleaner and follow the conventions of the language. As usual, all the examples are available over on GitHub.

Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.