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"
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"
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
"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())
}