Kotlin String replace() Tutorial
The String.replace() function in Kotlin is used to create a new string by replacing occurrences of a specified character or substring with another character or substring. It provides two overloaded versions to accommodate both character and string replacements. The resulting string is returned, leaving the original string unchanged.
Syntax
The syntax of the replace() function for character replacement is as follows:
fun String.replace(
oldChar: Char,
newChar: Char,
ignoreCase: Boolean = false
): String
And for string replacement:
fun String.replace(
oldValue: String,
newValue: String,
ignoreCase: Boolean = false
): String
The oldChar or oldValue parameter represents the character or substring to be replaced, newChar or newValue represents the replacement character or substring, and ignoreCase is an optional parameter to perform case-insensitive replacements.
Examples for String replace() function
1. Replace a Character in String using replace()
In this example, we’ll use replace() to replace occurrences of a specified character with another character in a given string.
- Take a string value in
originalString. - Call
replace()function onoriginalStringwith the values ofoldCharandnewCharas arguments. The function returns a new string with occurrences ofoldCharreplaced bynewChar. - You may print the original and resulting strings to the console output.
Kotlin Program
fun main() {
val originalString = "Hello, World!"
// Using replace() to replace occurrences of 'o' with '0'
val resultString = originalString.replace('o', '0')
// Printing the original and resulting strings
println("Original String:\n$originalString\n")
println("Result String:\n$resultString")
}
Output
Original String:
Hello, World!
Result String:
Hell0, W0rld!
2. Replace a Substring in String using replace()
In this example, we’ll use replace() to replace occurrences of a specified substring with another substring in a given string.
- Take a string value in
originalString. - Call
replace()function onoriginalStringwith the values ofoldValueandnewValueas arguments. The function returns a new string with occurrences ofoldValuereplaced bynewValue. - You may print the original and resulting strings to the console output.
Kotlin Program
fun main() {
val originalString = "Kotlin is fun!"
// Using replace() to replace occurrences of 'is' with 'rocks'
val resultString = originalString.replace("is", "rocks")
// Printing the original and resulting strings
println("Original String:\n$originalString\n")
println("Result String:\n$resultString")
}
Output
Original String:
Kotlin is fun!
Result String:
Kotlin rocks fun!
Summary
In this tutorial, we’ve covered the replace() function in Kotlin strings, its syntax, and how to use it to create new strings by replacing occurrences of a specified character or substring with another character or substring. This function is handy for string manipulation and substitution in various scenarios.