Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

581
Visualizações
How to use dynamic string substitution in Kotlin?

I'm looking for a Kotlin way to do a dynamic values substitution into a string. It is clear how to implement it, just want to check if there is something similar in standard library.

Could you help me to find a function which given template and data map returns a resulting string with all template keys replaced with their values?

fun format(template: String, data: Map<String, Any>): String { /* magic */ }

format("${a} ${b} ${a}", mapOf("a" to "Home", "b" to "Sweet))   // -> "Home Sweet Home"
over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

fun format(template: String, data: Map<String, String>): String {
  var retval = template
  data.forEach { dataEntry ->
    retval = retval.replace("\${" + dataEntry.key + "}", dataEntry.value)
  }
  return retval
}

// The $ signs in the template string need to be escaped to prevent
// string interpolation
format("\${a} \${b} \${a}", mapOf("a" to "Home", "b" to "Sweet"))
over 4 years ago · Santiago Trujillo Relatório

0

Not shorter than lukas.j's answer, just different (using Regex):

val regex = "\\\$\\{([a-z])}".toRegex()

fun format(template: String, data: Map<String, String>) =
    regex.findAll(template).fold(template) { result, matchResult ->
        val (match, key) = matchResult.groupValues
        result.replace(match, data[key] ?: match)
    }
over 4 years ago · Santiago Trujillo Relatório

0

I did not find any thing standard to solve the problem.

So here is a balanced (readability/performance/extensibility) solution also handling cases when some substitutions are undefined in dataMap.

makeString("\${a} # \${b} @ \${c}", mapOf("a" to 123, "c" to "xyz"))   // => "123 # ??? @ xyz"

--

object Substitutions {
    private val pattern = Pattern.compile("\\$\\{([^}]+)\\}")

    fun makeString(
        template: String, 
        dataMap: Map<String, Any?>, 
        undefinedStub: String = "???"
    ): String {
        val replacer = createReplacer(dataMap, undefinedStub)
        val messageParts = splitWithDelimiters(template, pattern, replacer)
        return messageParts.joinToString("")
    }

    private fun createReplacer(dataMap: Map<String, Any?>, stub: String): (Matcher) -> String {
        return { m ->
            val key = m.group(1)
            (dataMap[key] ?: stub).toString()
        }
    }

    private fun splitWithDelimiters(
        text: String,
        pattern: Pattern,
        matchTransform: (Matcher) -> String
    ): List<String> {
        var lastMatch = 0
        val items = mutableListOf<String>()
        val m = pattern.matcher(text)

        while (m.find()) {
            items.add(text.substring(lastMatch, m.start()))
            items.add(matchTransform(m))
            lastMatch = m.end()
        }

        items.add(text.substring(lastMatch))

        return items
    }
}
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda