The method replace() replaces all occurrences of a String in another String or all occurrences of a char with another char.

 

Available Signatures

public String replace(char oldChar, char newChar)
public String replace(CharSequence target, CharSequence replacement)

Example

@Test
void whenReplaceOldCharNewChar_thenCorrect() {
    String s = "wslcoms to basldung";

    assertEquals("welcome to baeldung", s.replace('s', 'e'));
}
@Test
void whenReplaceTargetReplacement_thenCorrect() {
    String s = "welcome at baeldung, login at your course";

    assertEquals("welcome to baeldung, login to your course", s.replace("at", "to"));
}
Next »
Java String.replaceAll()
« Previous
Java String.regionMatches()
Java bottom

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

>> CHECK OUT THE COURSE
Generic footer banner
Comments are closed on this article!