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  av  a 2 s  .co  m
    System.out.println(newStr);
  }
}

Result

Related Topics

Exercise