If have a string and a number of character ranges ...
# getting-started
h
If have a string and a number of character ranges and I want to replace each range with inside the string with a different one which doesn't have the same length. So, e.g. if I have "Carla and Bob went to school" and I want to replace the ranges of the names with e.g.
<name>Carla</name>
to finally get "<name>Carla</name> and <name>Bob</name> went to school". Is there an easy way in Kotlin to achieve this without tracking the lengths that I have already inserted?
d
The input must be the ranges? Or do you actually have a list of words you want to replace?
h
No, the input are character-ranges the map into the original string.
I can implement it manually by replacing one after another and keeping track of the additionally inserted characters, but I thought maybe this is something someone has already solved in a better way.
p
If you don’t want to keep track of number of inserted characters then just start replacing from the end of the string. Or I would recommend to create a
StringBuilder
and append part by part while using input ranges on original string.
h
@Pavlo Liapota Yep, good idea. My hope was that something like
String.replaceRange(range: IntRange, replacement: CharSequence)
for several ranges exists which does the job. I'm going to follow your advice.
👍 1