Got stuck on logic of a given array

Viewed 75

I have this code:

val 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) // <-- I know this is the culprit, but I got stuck. don't know what to do anymore
}
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> instead

notice the data-id value is incrementing in accordance to the list

The main problem is that the string variable and the listOf will be dynamic.

for example:

val string = "<p></p>this<p></p>that<p></p>"
val arrs = listOf("<p data-id=\"1\"></p>", "<p data-id=\"2\"></p>", "<p data-id=\"3\"></p>")

or

val string = "<p></p>this<p></p><p></p>that"
val arrs = listOf("<p data-id=\"1\"></p>", "<p data-id=\"2\"></p>", "<p data-id=\"3\"></p>")

so on and so forth

2 Answers

There are a couple of issues,

  1. .replace will replace all occurences in the string. This is likely what you don't want. Maybe you need to use replaceFirst

  2. replacedString is overwritten in every pass of the forEach. Therefore, it will only have the value of the last iteration, which is result of what you observe. Ideally use a StringBuilder here and append the replaceString result on every pass.

So in effect,

var replacedString = string 
arrs.forEach {
    val pTag = "<p></p>"
    replacedString = replacedString.replaceFirst(pTag, it))
} 
println(replacedString)

Hope that gets you moving along

fun main(args: Array<String>) {
    println(replacePtag("<p></p>this<p></p><p></p>that"))
    //<p data-id=1></p>this<p data-id=2></p><p data-id=3></p>that
    println(replacePtag("<p></p>this<p></p>"))
    //<p data-id=1></p>this<p data-id=2></p>
}

fun replacePtag(inputHtml: String): String {
    val tag = "<p></p>"
    fun p(id: Int): String = "<p data-id=$id></p>"
    var input = inputHtml
    var currentId = 1
    var tmp = input.replaceFirst(tag, p(currentId))
    currentId++
    while (tmp != input) {
        input = tmp
        tmp = tmp.replaceFirst(tag, p(currentId))
        currentId++
    }
    return input
}
Related