Searching and replacing text

Kotlin:
Searching and replacing text

How to:

Kotlin simplifies text manipulation through its standard library. Below, see how you use replace to swap out words.

fun main() {
    val originalText = "Kotlin is fun, Kotlin is pragmatic!"
    val newText = originalText.replace("pragmatic", "cool")

    println(newText) // Output: Kotlin is fun, Kotlin is cool!
}

For regex patterns:

fun main() {
    val regex = "Kotlin".toRegex()
    val originalText = "Kotlin is fun, Kotlin is pragmatic!"
    val newText = regex.replace(originalText, "Java")

    println(newText) // Output: Java is fun, Java is pragmatic!
}

Deep Dive

Rewriting text is old as print, but in programming, it surged with early text processors. Alternatives? Sure – find & replace functions in editors, command-line tools like sed. In Kotlin specifically, you have regex and plain string methods at your disposal.

replace is straightforward for simple text; Regex gives you a Swiss Army knife for patterns. Regexes are powerful but trickier – they use special syntax to pattern match. Think about regex as playing Where’s Waldo, but you’re crafting the rules on what Waldo wears.

Implementation gotchas? Remember, Kotlin’s String is immutable. Methods that alter text return new strings; they don’t change the original.

See Also