Any ideomatic way of inserting a String at a speci...
# getting-started
d
Any ideomatic way of inserting a String at a specific position in another string?
k
I think you're stuck with
substring
and
+
.
d
Currently using
replace
, even though I know the exact position I need... 😛. Maybe two substrings are more efficient? This is for an api that constantly gets hit.
k
Yeah definitely do substrings.
👍🏼 1
Or maybe
StringBuilder(string)
and then
insert
d
I was thinking of replaceRange, but then I'd do 5..5?
👍 1
The extra allocation of a StringBuilder is worth it?
k
I'm not sure, if it really matters that much you need to benchmark it.
s
ooc what does the
substring
implementation look like? my first guess was to just use
take
and
takeLast
but maybe I’m not taking something important into account
d
Yup the replaceRange seems to work... I wonder if it has the same overhead as replace... the only thing is one has to remeber to re-add the replaced character...
k
Surely the range one is faster since it doesn't need to search the string?
d
Probably... In my current Ktor project I can't ctrl-click it... I guess I'll have to look it up after I finish with this task. I guess this is too much of an edge-case to have an
insertAt(position: Int, stringToInsert: String)
in the stdlib.... thanks anyways!