Daniel
02/08/2020, 12:16 PMfun String.setCharAt(index: Int, char: Char) = StringBuilder(this)
.apply {
setCharAt(index, char)
}.toString()
Googling franticly, but I can't find an inbuild method for thisMatteo Mirk
02/10/2020, 9:12 AMval s = "abcde"
println(s.replaceRange(2..2, "X"))
// -> abXde
you can encapsulate it in your extension if you likeMatteo Mirk
02/10/2020, 9:16 AMsetCharAt()
and set()
on StringBuilderDaniel
02/11/2020, 6:25 PMfun String.replace(index: Int, newChar: Char) =
transform {
setCharAt(index, newChar)
}
private fun String.transform(transform: StringBuilder.() -> Unit) =
StringBuilder(this).apply(transform).toString()
kevin.cianfarini
02/12/2020, 2:58 AMfun String.replaceAt(c: Char, index: Int): String {
return this.toCharArray().apply {
set(index, c)
}.joinToString()
}
Matteo Mirk
02/12/2020, 9:15 AMfun 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 🙂Daniel
02/12/2020, 6:37 PMtransform
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! 🙂Matteo Mirk
02/13/2020, 2:52 PM