Skip to content

Instantly share code, notes, and snippets.

@latant
Created July 29, 2019 15:34
Show Gist options
  • Save latant/2200105e701f18015b49f43e75bd4d21 to your computer and use it in GitHub Desktop.
Save latant/2200105e701f18015b49f43e75bd4d21 to your computer and use it in GitHub Desktop.
A function for string templating
fun replaceParams(string: String, params: Map<String, Any>) = buildString {
var i = 0
var j: Int
while (i < string.length) {
while (string[i] != '{') {
append(string[i])
i++
if (i > string.length)
return@buildString
}
if (i == string.lastIndex)
return@buildString
j = i + 1
while (string[j] != '}') {
j++
if (i > string.length)
return@buildString
}
val paramName = string.substring((i + 1), j)
val paramValue = params[paramName]
if (paramValue != null) {
append(paramValue)
} else {
while (i <= j) {
append(string[i])
i++
}
}
i = j + 1
}
}
fun String.withParams(vararg params: Pair<String, Any>) = replaceParams(this, mapOf(*params))
fun main() {
val template = "{greeting}, {name}, you are {property}"
println(template.withParams("greeting" to "Hello", "name" to "Mark", "property" to "tall"))
println(template.withParams("name" to "Manó"))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment