Googling franticly, but I can't find an inbuild method for this
m
Matteo Mirk
02/10/2020, 9:12 AM
you could use replaceRange from Kotlin std lib:
Copy code
val s = "abcde"
println(s.replaceRange(2..2, "X"))
// -> abXde
you can encapsulate it in your extension if you like
Matteo Mirk
02/10/2020, 9:16 AM
anyway “setCharAt” is misleading since strings are immutable, the closest mutating methods are in fact
setCharAt()
and
set()
on StringBuilder
d
Daniel
02/11/2020, 6:25 PM
Good idea with the replaceRange! And agree with the setCharAt.
At the end I settled with:
Copy code
fun String.replace(index: Int, newChar: Char) =
transform {
setCharAt(index, newChar)
}
private fun String.transform(transform: StringBuilder.() -> Unit) =
StringBuilder(this).apply(transform).toString()
k
kevin.cianfarini
02/12/2020, 2:58 AM
Copy code
fun String.replaceAt(c: Char, index: Int): String {
return this.toCharArray().apply {
set(index, c)
}.joinToString()
}
m
Matteo Mirk
02/12/2020, 9:15 AM
Nice @Daniel, but isn’t this shorter?
Copy code
fun String.replaceAt(index: Int, newChar: Char) = replaceRange(index..index, newChar.toString())
I think it conveys the point straight when readin it, while in your solution I’d have to read two functions to understand the mechanism. Less code, improved maintainability 🙂
d
Daniel
02/12/2020, 6:37 PM
The replaceRange is also a good option! In my case the
transform
is used multiple times in the file so its "known" so to speak. Also I think its nice that you immedeately see that only one char is replaced (setCharAt). But thats totally opinion of course! 🙂
m
Matteo Mirk
02/13/2020, 2:52 PM
Sure, if it works for your codebase go for it! Didn’t want to sound pedantic, I’m just a maniac of short clean code 😆