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