In this tutorial, you shall learn how to convert a given string into a Set of characters in Kotlin, using String.toSet() function, with examples.

Kotlin – Convert a String to Set of Characters

To convert a given string into Set of characters in Kotlin, call toSet() method on this String. toSet() returns a Set<Char> object with all the unique characters of this string as elements.

Example

In the following example, we take a string in str, and convert it into a set of characters using toSet() method.

Main.kt

</>
Copy
fun main(args: Array<String>) {
    var str = "hello world"
    var result = str.toSet()
    println(result)
}

Output

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

Conclusion

In this Kotlin Tutorial, we learned how to convert a given string into set of characters using String.toSet() method, with the help of Kotlin example programs.