KOTLIN / JAVA: String doesn't get replaced in a loop

Viewed 76
val string = "8% of 25 is the same as <img src=\"/someimage.png\" class=\"limit\">There are no heroes in a punk rock band <img src=\"/someimage.png\" class=\"limit\">"

val arraySearchInTheStringVariableAbove = arrayOf(
    "<img src=\"/someimage.png\" class=\"limit\">", 
    "<img src=\"/someimage.png\" class=\"limit\">"
)

val arrayReplacementInTheStringVariableAbove = arrayOf(
    "<img src=\"/someimage.png\" class=\"another-limit\" data-id=\"1\">", 
    "<img src=\"/someimage.png\" class=\"another-limit\" data-id=\"2\">"
)

arraySearchInTheStringVariableAbove.forEachIndexed { index, it ->
    string.replace(it, arrayReplacementInTheStringVariableAbove[index])
}

println(string)

the string doesn't get replaced. still shows:

8% of 25 is the same as <img src="/someimage.png" class="limit">There are no heroes in a punk rock band <img src="/someimage.png" class="limit">

where it should have been

8% of 25 is the same as <img src="/someimage.png" class="another-limit" data-id="1">There are no heroes in a punk rock band <img src="/someimage.png" class="another-limit" data-id="2">

notice the <img> tag gets replaced sequentially

2 Answers

Java and Kotlin strings are immutable and not editable in place. replace() returns a new string that you're throwing away.

One way to fix that is change the val string to a var string and assign the returned string back to it.

String is immutable, every time you transform it, it creates new String in StringPool, you can assign it back to same string as var

var string = "8% of 25 is the same as <img src=\"/someimage.png\" class=\"limit\">There are no heroes in a punk rock band <img src=\"/someimage.png\" class=\"limit\">"

val arraySearchInTheStringVariableAbove = arrayOf(
    "<img src=\"/someimage.png\" class=\"limit\">", 
    "<img src=\"/someimage.png\" class=\"limit\">"
)

val arrayReplacementInTheStringVariableAbove = arrayOf(
    "<img src=\"/someimage.png\" class=\"another-limit\" data-id=\"1\">", 
    "<img src=\"/someimage.png\" class=\"another-limit\" data-id=\"2\">"
)

arraySearchInTheStringVariableAbove.forEachIndexed { index, it ->
    string = string.replace(it, arrayReplacementInTheStringVariableAbove[index])
}

println(string)
Related