Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why am I geting a blank when I run this string funtion in Kotlin?

So I was solving a problem that required me to put unique characters in a string without using a data structure.

fun main(){
    val s1 = "fhfnfnfjuw"
    val s2 = "Osayuki"
    val s3 = "Raymond"
    val s4 = "Aseosa"

  uniqueChar(s1)
}


fun uniqueChar(s: String){
    val updatedString = ""
    s.forEach {c ->
        if (!updatedString.contains(c)){
            updatedString.plus(c)
        }
    }
    println(updatedString)

}

And getting this error
enter image description here

I’m not sure what’s going on and why I’m getting a blank. I’m sure it’s an easy fix, but I can’t see it. Any help is appreciated.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

updatedString.plus(c) does not change updatedString. It creates a new string, including the character c. Since you don’t do anything with that, the new string goes…nowhere.

Instead, you probably wanted updatedString = updatedString.plus(c) — or something better with StringBuilder, but that’s the closest version to your code.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading