0

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.

Egor Klepikov
  • 3,386
  • 5
  • 19
  • 34
OEThe11
  • 341
  • 2
  • 11
  • 1
    For those of us who don't have a magnifying glass to hand (along with those who use screen readers, or mobile devices, &c), could you [post the error as text instead of an image](/questions/285551/why-should-i-not-upload-images-of-code-data-errors-when-asking-a-question) please? – gidds Jul 29 '22 at 22:10
  • 1
    fyi `process finished with exit code 0` isn't an error - lots of command-line stuff returns an exit code, and `0` usually means success. So nothing's going wrong in your script, it's just not doing what you expect it to – cactustictacs Jul 29 '22 at 22:18

1 Answers1

1

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.

Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413