Start learning free

LESSON 62 OF 348 · STRINGS I

String Replace in Scala in Scala

Lesson

In Scala, you can replace part of a string using the replace() method:

s.replace(old, new)          // replaces all occurrences
s.replaceFirst(regex, new)   // replaces first match

Here are some examples:

var sentence = "I love cats"
var result = sentence.replace("cats", "dogs")
println(result)  // "I love dogs"

var text = "aaa"
println(text.replace("a", "b"))  // "bbb"

replace() returns a new String — the original is not modified.


Assignment
Follow the Coding Tutorial and replace "cats" with "dogs" in sentence!


Hint
Use sentence.replace("cats", "dogs") and assign it to result.

STEP 1 OF 1
    Ctrl + Enter to check

    String Replace in Scala

    Keep going with ScalaAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free