mending3
02/24/2021, 4:50 AMval string = "<p></p>this<p></p>"
val arrs = listOf("<p data-id=\"1\"></p>", "<p data-id=\"2\"></p>")
var replacedString = ""
arrs.forEach {
val pTag = "<p></p>"
replacedString = string.replace(pTag, it)
}
println(replacedString)
It should show <p data-id="1"></p>this<p data-id="2"></p>
, but it shows
<p data-id="2"></p>this<p data-id="2"></p>
insteadnanodeath
02/24/2021, 4:51 AMnanodeath
02/24/2021, 4:52 AMmending3
02/24/2021, 4:53 AMmending3
02/24/2021, 4:53 AMmending3
02/24/2021, 4:54 AMnanodeath
02/24/2021, 4:56 AM"<p data-id=\"${arrs.first()}\"></p>this<p data-id=\"${arrs.last()}\"></p>"
mending3
02/24/2021, 5:00 AMlistOf
would be dynamic
so if I have:
val arrs = listOf("1", "2", "3")
the transformed string would look:
<p data-id="1"></p>this<p data-id="2"></p><p data-id="3"></p>
or
<p data-id="1"></p>this<p data-id="2"></p>that<p data-id="3"></p>
so on and so forthnanodeath
02/24/2021, 5:01 AMmending3
02/24/2021, 5:02 AMmending3
02/24/2021, 5:05 AMvar replacedString = ""
arrs.forEach {
val pTag = "<p></p>"
replacedString = string.replace(pTag, it)
}
println(replacedString)
this doesn't work
it always gets the last index so the data-id
value is 3
nanodeath
02/24/2021, 5:10 AMzip
only produces a collection as long as the shorter one though.mending3
02/24/2021, 5:13 AMletters
variable?nanodeath
02/24/2021, 5:15 AMmending3
02/24/2021, 6:00 AMletters
variable?mending3
02/24/2021, 6:01 AMmending3
02/24/2021, 6:07 AMPetter Måhlén
02/24/2021, 7:08 AMreplacedString = string.replace(…)
. you’re overwriting the replacedString
var on each iteration, and reading from the original string
Dave K
02/24/2021, 7:19 AMval values = string.split(pTag)
arrs.zip(values + List(arrs.length - values.length) { “” }) { a,b -> listOf(a,b) }.flatten().joinToString(“”)
So essentially remove all the ptags and produce a list of this (and that), and then pad that list with empty strings so that it’s the same length as the list of arrs. Then zip the two lists together finally joining them all into a single string.Dave K
02/24/2021, 7:22 AMarrs.map { “<p data-id=\”$it\”></p>” }.zip...
Dave K
02/24/2021, 7:22 AMDave K
02/24/2021, 7:26 AMPetter Måhlén
02/24/2021, 7:28 AMDave K
02/24/2021, 7:32 AMnkiesel
02/24/2021, 7:29 PMstring
instead of replacedString
in your loop iterations. Thus, every iteration starts with the same data and overwrites whatever the previous iteration did
2. String::replace
replaces all matches in the String and not just the first one. Thus, your 2nd (and final) iteration does replacedString = "<p></p>this<p></p>".replace("<p></p>", "<p data-id=\"2\"></p>")
and you end up with the result you see.
Minimal changes to your code to provide the desired output:
var replacedString = string
arrs.forEach {
val pTag = "<p></p>"
replacedString = replacedString.replaceFirst(pTag, it)
}
Matteo Mirk
02/25/2021, 11:00 AM