Java - String String Replacing

Introduction

replace() method replaces an old character with a new character.

It returns a new String object by replacing all occurrences of the old character by the new character.

For example,

String oldStr = new String("tooth");

// o in oldStr will be replaced by e. newStr will contain "teeth"
String newStr = oldStr.replace('o', 'e');

Demo

public class Main {
  public static void main(String[] args) {
    String oldStr = new String("tooth");

    // o in oldStr will be replaced by e. newStr will contain "teeth"
    String newStr = oldStr.replace('o', 'e');

    System.out.println(oldStr);/*from w  w w . j a va 2 s.  c  o  m*/
    System.out.println(newStr);
  }
}

Result

Related Topics

Exercise