Kotlin – String Replace
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. In this tutorial, we shall go through examples where we shall replace an old value (string) with a new value (another string) for each occurrence of oldValue in a String, ignoring and not ignoring oldValue’s character case.
Syntax
Syntax of String.replace method is
String.replace(oldValue: String, newValue: String, ignoreCase: Boolean = false): String
oldValue : The string which has to be replaced with newValue for each occurrence of oldValue in String.
ignoreCase : [Optional] If true, character case of oldValue would be not be taken into account to find a match in String. If false, character case would be considered while finding a match for oldValue in the String. The default value of ignoreCase is false.
Examples
1. Replace substring with another
In the following Kotlin Example, we shall replace substring Programs
with Examples
value in the string, Kotlin Tutorial - Replace String - Programs
.
example.kt
fun main(args: Array<String>) {
var str = "Kotlin Tutorial - Replace String - Programs"
val oldValue = "Programs"
val newValue = "Examples"
val output = str.replace(oldValue, newValue)
print(output)
}
Output
Kotlin Tutorial - Replace String - Examples
2. String Replace – Ignore Case
In the following Kotlin Example, we shall replace PROGRAMS string with Examples value in the string, Kotlin Tutorial – Replace String – Programs ignoring character case. To ignore case, we pass ignoreCase = true as third argument.
example.kt
fun main(args: Array<String>) {
var str = "Kotlin Tutorial - Replace String - Programs"
val oldValue = "PROGRAMS"
val newValue = "Examples"
val output = str.replace(oldValue, newValue, ignoreCase = true)
print(output)
}
Output
Kotlin Tutorial - Replace String - Examples
Conclusion
In this Kotlin Tutorial – Kotlin Replace String, we have learnt how to replace a old value with a new value in a string. We have also dealt with ignoring case while replacing the string with Kotlin Examples.