21

How to replace a part of a string with something else in Kotlin?

For example, changing "good morning" to "good night" by replacing "morning" with "night"

1

2 Answers 2

29
fun main(args: Array<String>) {
  var a = 1
  // simple name in template:
  val s1 = "a is $a" 

  a = 2
  // arbitrary expression in template:
  val s2 = "${s1.replace("is", "was")}, but now is $a"
  println(s2)
}

OUPUT: a was 1, but now is 2

Sign up to request clarification or add additional context in comments.

Comments

14
"Good Morning".replace("Morning", "Night")

It's always useful to search for functions in the Kotlin standard library API reference. In this case, you find the replace function in Kotlin.text:

/**
 * Returns a new string with all occurrences of [oldChar] replaced with [newChar].
 */
public fun String.replace(oldChar: Char, newChar: Char, ignoreCase: Boolean = false): String {
    if (!ignoreCase)
        return (this as java.lang.String).replace(oldChar, newChar)
    else
        return splitToSequence(oldChar, ignoreCase ignoreCase).joinToString(separator = newChar.toString())
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.