Kotlin String replace() with Substrings, Characters, and Regex
Kotlin provides the replace() function to replace matching text in a string. You can replace a substring, replace individual characters, ignore letter case, or use a regular expression for pattern-based replacements. Because Kotlin strings are immutable, replace() returns a new string and does not modify the original value.
Kotlin String replace() Syntax and Parameters
The following overload replaces every literal occurrence of oldValue with newValue.
String.replace(oldValue: String, newValue: String, ignoreCase: Boolean = false): String
oldValueis the substring to find.newValueis the text inserted in place of every match.ignoreCasecontrols case-sensitive matching. Its default value isfalse.- The return value is a new
Stringcontaining the replacements.
When ignoreCase is false, uppercase and lowercase letters must match exactly. Set it to true when values such as Programs, PROGRAMS, and programs should be treated as matches.
Kotlin String Replacement Examples
1. Replace a Substring with Another String in Kotlin
In the following Kotlin example, the substring Programs is replaced with Examples in 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
The original value stored in str remains unchanged. The replaced text is stored in output.
2. Replace a Kotlin String While Ignoring Case
In the following example, PROGRAMS is used as the old value even though the source string contains Programs. Passing ignoreCase = true allows the differently cased text to match.
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
3. Replace All Occurrences of a Substring in Kotlin
The standard string overload of replace() replaces every non-overlapping occurrence of the specified substring. Kotlin does not require a separate Java-style replaceAll() call for literal text replacement.
fun main() {
val text = "red car, red bus, red bicycle"
val result = text.replace("red", "blue")
println(result)
}
Output
blue car, blue bus, blue bicycle
4. Replace a Character in a Kotlin String
Kotlin includes a character overload of replace(). Use character literals in single quotes when replacing one character with another.
string.replace(oldChar: Char, newChar: Char, ignoreCase: Boolean = false)
fun main() {
val text = "banana"
val result = text.replace('a', 'o')
println(result)
}
Output
bonono
Every matching a is replaced. To replace only one character at a known position, use replaceRange() as shown later in this tutorial.
5. Replace Only the First Matching Substring in Kotlin
Use replaceFirst() when only the first occurrence should change. Later matches remain in the returned string.
fun main() {
val text = "one fish, two fish, three fish"
val result = text.replaceFirst("fish", "bird")
println(result)
}
Output
one bird, two fish, three fish
6. Replace Text Using a Kotlin Regular Expression
Use the Regex overload when the text to replace follows a pattern. The next example replaces every sequence of one or more digits with #.
string.replace(regex: Regex, replacement: String)
fun main() {
val text = "Order 125 contains 3 items"
val result = text.replace(Regex("\\d+"), "#")
println(result)
}
Output
Order # contains # items
Use the ordinary string overload when the old value is literal text. Use Regex only when pattern matching is required, because characters such as ., *, +, and ? have special meanings in regular expressions.
7. Build a Dynamic Replacement with Regex Match Values
The transform overload receives each regular-expression match. A lambda can inspect the matched value and calculate its replacement.
fun main() {
val text = "Items: 4, Boxes: 7"
val result = Regex("\\d+").replace(text) { match ->
(match.value.toInt() * 2).toString()
}
println(result)
}
Output
Items: 8, Boxes: 14
8. Replace a Character at a Specific String Index
The character overload replaces matching characters throughout a string. To replace the character at one specific index, replace the one-character range with replaceRange().
fun main() {
val text = "Kotlin"
val index = 1
val result = text.replaceRange(index, index + 1, "a")
println(result)
}
Output
Katlin
The index must refer to a valid character position. Check that it belongs to text.indices before using an index obtained at runtime.
9. Remove a Substring by Replacing It with an Empty String
To remove matching text, use an empty string as the replacement value.
fun main() {
val text = "Kotlin String Tutorial"
val result = text.replace(" String", "")
println(result)
}
Output
Kotlin Tutorial
Kotlin replace(), replaceFirst(), and replaceRange() Comparison
| Function | Use | Replacement scope |
|---|---|---|
replace() | Replace a literal substring, character, or regex pattern | All matching occurrences |
replaceFirst() | Replace the first literal or regex match | First matching occurrence |
replaceRange() | Replace text between specified indexes | Selected index range |
These functions operate on strings. Replacing an element in a Kotlin MutableList is a separate operation, normally performed by assigning a new value to an index, such as items[1] = "new value".
Kotlin String Replacement QA Checklist
- Confirm whether the replacement should affect every match or only the first match.
- Check whether substring matching should be case-sensitive.
- Use character literals for character replacement and string literals for substring replacement.
- Use
Regexonly when the search value is a pattern. - Validate an index before calling
replaceRange(). - Store or return the result because the original Kotlin string is not modified.
Kotlin String replace() FAQs
Does Kotlin replace() replace every occurrence?
Yes. The standard replace() overloads replace every non-overlapping match. Use replaceFirst() when only the first occurrence should be changed.
Does Kotlin have a String replaceAll() function?
Kotlin uses replace() to replace all literal substring or character matches. For pattern-based replacement, pass a Regex to replace().
How do I replace text without considering case in Kotlin?
Use the string or character overload and pass ignoreCase = true, as in text.replace("old", "new", ignoreCase = true).
How do I replace one character at a specific index?
Use replaceRange(index, index + 1, replacement). Validate the index first if it comes from user input or another runtime calculation.
Why does calling replace() not change my original Kotlin string?
Kotlin strings are immutable. Assign the returned value to a variable, such as text = text.replace("old", "new"), or pass the result directly to the next operation.
Summary of Kotlin String Replacement
In this Kotlin Tutorial, we learned how to replace substrings and characters with replace(), perform case-insensitive replacement, replace only the first match, use regular expressions, calculate dynamic replacements, remove text, and replace a character at a specific index.
TutorialKart.com