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
| Parameter | Type | Description |
|---|---|---|
| target | CharSequence | What to replace — plain text, not a regular expression. There is also a char version. |
| replacement | CharSequence | The 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/cRemoving characters — replace with an empty string:
void main() {
String phone = "+1 (555) 123-45";
IO.println(phone.replace(" ", "").replace("-", ""));
}Output:
+1(555)12345Notes
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
- String.replaceAll() — Replaces every match of a regular expression.
- StringBuilder.append() — Adds a value to the end of a StringBuilder.
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.