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()
Course – LS – All

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

>> CHECK OUT THE COURSE
res – REST with Spring (eBook) (everywhere)
Comments are closed on this article!