Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to replace text in a string

Short answer

replace() replaces every occurrence of a substring:

void main() {
    String text = "I like cats. Cats are cute.";
    IO.println(text.replace("cats", "dogs"));
}

Output:

I like dogs. Cats are cute.

Replacement is case-sensitive, so Cats with a capital letter stayed.

A regular expression

replaceAll() takes a regular expression. The (?i) flag turns off case sensitivity:

void main() {
    String text = "I like cats. Cats are cute.";
 
    IO.println(text.replaceAll("(?i)cats", "dogs"));
    IO.println("Phone: 8-900-123-45-67".replaceAll("\\D", ""));
}

Output:

I like dogs. dogs are cute.
89001234567

Only the first occurrence

replaceFirst() replaces just the first match:

void main() {
    IO.println("a-b-c".replaceFirst("-", "+"));
}

Output:

a+b-c

Several replacements

Keep "from — to" pairs in a Map and apply them in a loop:

void main() {
    var replacements = Map.of("{name}", "Anna", "{city}", "Berlin");
    String text = "Hi, {name} from {city}!";
 
    for (var entry : replacements.entrySet()) {
        text = text.replace(entry.getKey(), entry.getValue());
    }
    IO.println(text);
}

Output:

Hi, Anna from Berlin!

Common mistake

Strings are immutable: replace() returns a new string, and the original stays the same:

void main() {
    String text = "hello";
    text.replace("h", "H");
    IO.println(text);
 
    text = text.replace("h", "H");
    IO.println(text);
}

Output:

hello
Hello

Functions used in this recipe

Thanks for reading!

Donate to the site — we work hard for you.