Kotlin unique characters not working

fun getUniqueChars( text: String) : List<Char> {
    var res : MutableList<Char> = mutableListOf<Char>()
    var index = 1
    for (char in text) {
        val result = text.slice(index..text.length - 1)
        var index3 = 0
        for (char2 in result) {
            var index2 = 0
            if( char2 != char && index3 == result.length - 1) {
                res.add(index2, char)
                index2++
            } else if( char2 != char) {
                index3++
            }
        }
        index++
    }
    return res
}

This program does not. work-out the last unique character.

Don’t worry I worked it out, not very good code.

you could also just use String.toSet() if you haven’t found that already :slightly_smiling_face:

I did not work it out as happens.


fun occurrencesOfCharacters(text: String): Map<Char, Int> {
    var charCount: MutableMap<Char, Int> = mutableMapOf()
    var count2 = 0
    for( char in text) {
        if( count2 == 0) {
            charCount.put(char, 0)
                count2++
        } else {
            var count = charCount.get(char)
            charCount.put( char, count!! + 1)
        }
    }
    return charCount
}

This works apart from causing an null pointer exception.

I was trying to write a program that works out the number of characters and thought the best way was to work out which unique characters.

If you wish to count charaters in a text then there is a very quick way straight from the standard library functions:

val charCounts = text.groupingBy { it }.eachCount()

Thanks