Get unique characters in a String in Kotlin
To get unique characters in a given string in Kotlin, you can convert the string to a set of characters using String.toSet()
function. Since a set can contain only unique items, only unique characters from given string are stored in the set.
str.toSet()
The function returns a Set object. We can iterate over this object using a For loop statement.
Examples
Print unique characters in the string “banana”
In the following program, we take a string value in str
and print out the unique characters in this string.
Kotlin Program
fun main() {
val str = "banana"
val uniqueChars = str.toSet()
for (char in uniqueChars) {
println(char)
}
}
Output
b
a
n