.replace()
StevenSwiniarski474 total contributions
Published Apr 16, 2022
Contribute to Docs
The String
class’ .replace()
method returns a new string where all instances of a given value are switched with a new value.
Syntax
string.replace(char oldValue, char newValue);
A char represents a single character. Other valid inputs for the .replace()
method include the following:
- An instance of the
Character
class that resolves to a single character. - A
CharSequence
interface that represents a sequence of characters (theString
class is one implementation of this interface).
In any case, the returned result will always be a new String
object with all instances of oldValue
replaced with the newValue
.
Example
The example below tests a string s
with the usage of char values, Character
instances, and a CharSequence
where a substring, “Hello”, is replaced with “Goodbye” and reassigned:
public class ReplaceMe {public static void main(String args[]) {String s = "Hello World!";System.out.println("Original String: " + s);char testA = 'e';System.out.println("With primitive char: " + s.replace(s.charAt(2), testA));Character testB = new Character('o');System.out.println("With Character class: " + s.replace(s.charAt(6), testB));CharSequence testC = "Goodbye";System.out.println("With CharSequence: " + s.replace("Hello", testC));}}
This results in the following output:
Original String: Hello World!With primitive char: Heeeo Wored!With Character class: Hello oorld!With CharSequence: Goodbye World!
Looking to contribute?
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.