In this tutorial, you shall learn how to get unique characters in a given string in Kotlin, using List.distinct() function, with examples.

Kotlin – Get Unique Characters in String

To get unique characters in string in Kotlin, fist convert the string to a list of characters using String.toMutableList() function, and then get the distinct of these characters using List.distinct() function.

Example

In the following program, we take a string in str, get the unique characters in the string into a list, and print them to output.

Main.kt

</>
Copy
fun main() {
    var str = "helloworld"
    var chars = str.toMutableList()
    var uniqueChars = chars.distinct()
    println(uniqueChars)
}

Output

[h, e, l, o, w, r, d]

Conclusion

In this Kotlin Tutorial, we learned how to get the unique or distinct characters in a string.