Might there be a better way to change a character ...
# codereview
d
Might there be a better way to change a character in a string?
Copy code
fun String.setCharAt(index: Int, char: Char) = StringBuilder(this)
        .apply {
            setCharAt(index, char)
        }.toString()
Googling franticly, but I can't find an inbuild method for this
m
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
anyway “setCharAt” is misleading since strings are immutable, the closest mutating methods are in fact
setCharAt()
and
set()
on StringBuilder
d
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
Copy code
fun String.replaceAt(c: Char, index: Int): String {
    return this.toCharArray().apply {
        set(index, c)
    }.joinToString()
}
m
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
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
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 😆