Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

String.replace()

Replaces every occurrence of a substring or a character with another string.

Available since: Java 5

Syntax

public String replace(CharSequence target, CharSequence replacement)

Parameters

ParameterTypeDescription
targetCharSequenceWhat to replace — plain text, not a regular expression. There is also a char version.
replacementCharSequenceThe replacement text.

Return value

StringA new string with the replacements.

Examples

Replacing every occurrence:

void main() {
    String text = "one two one";
    IO.println(text.replace("one", "1"));
    IO.println("a-b-c".replace('-', '/'));
}

Output:

1 two 1
a/b/c

Removing characters — replace with an empty string:

void main() {
    String phone = "+1 (555) 123-45";
    IO.println(phone.replace(" ", "").replace("-", ""));
}

Output:

+1(555)12345

Notes

Despite the name, replace() replaces every occurrence, not just the first one. The difference from replaceAll() is that replace() looks for plain text, while replaceAll() takes a regular expression where ., +, ( have special meaning.

See also

Related recipes

In the tutorial

  • String methods — The main String methods in Java: searching, substring, changing case, strip, replace, split, join, repeat and string checks.

Thanks for reading!

Donate to the site — we work hard for you.