String in Kotlin is immutable cannot work like
ans[index] = value
I wonder they are a simple way to make it work
String in Kotlin is immutable cannot work like
ans[index] = value
I wonder they are a simple way to make it work
If StringBuilder is your decision, you could also use .insert()
, and create something like this:
fun String.addCharAtIndex(char: Char, index: Int) =
StringBuilder(this).apply { insert(index, char) }.toString()
Calling it will work like this:
val s = "hello orld".addCharAtIndex('w', 6)
println(s) // this will print 'hello world'
The thing is, we did not add to the existing string, we created a new one, and left the old one for the GC. This will mean that if the original string had 1MB, we would now use up 2MB (until the GC does it's job). If the string is not huge and we have enough memory, this code should be ok.
I'm not sure how one would actually add to a String without creating a new one, since String is immutable in Kotlin.
edit:
Apparently as @al3c suggested there already is a function that does this called replaceRange()
that will work for any CharSequence
. It will probably work better than the custom one I showed above (it will also work for adding a CharSequence
, not only a Char
, if desired).
You would use it like this:
val string = "hello orld".replaceRange(6,6,"w")
println(string) //this will print 'hello world'
But just to note, this will also create a new String
. See from the docs:
Returns a char sequence with content of this char sequence where its part at the given range is replaced with the replacement char sequence.
If you want to make frequent changes, then you can convert it to CharArray
first, make changes, and then joinToString
.
val index = 3
val str = "one two"
val ans = str.toCharArray().also { it[index] = '_' }.joinToString("")
print(ans)
Although, if it's only a one time change, it would be better to use StringBuilder
as others have suggested.
ans[index] = value
(which was also a replacement operation). I figured that may be the OP's aim is to have the string in a modifiable condition, mainly from their comment to the original question. –
Lugworm © 2022 - 2024 — McMap. All rights reserved.
replaceRange
is your best bet: kotlinlang.org/api/latest/jvm/stdlib/kotlin.text/…ans = ans.replaceRange(index, index+1, value)
– Selachian