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"
The basic String Replace method in Kotlin is String. replace(oldValue, newValue). ignoreCase is an optional argument, that could be sent as third argument to the replace() method.
Strings are immutable in Kotlin. That means their values cannot be changed once created. To replace the character in a string, you will need to create a new string with the replaced character.
Since strings are immutable in Kotlin, we can't remove characters from it. However, we can create a new string with the first n characters removed. This can be done using the substring() function with the starting index n , which creates a substring starting from position n till its end.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With