Java.lang.String.replace() Method

Advertisements


Description

The java.lang.String.replace(char oldChar, char newChar) method returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.

Declaration

Following is the declaration for java.lang.String.replace() method

public String replace(char oldChar, char newChar)

Parameters

  • oldChar -- This is the old character.

  • newChar -- This is the new character.

Return Value

This method returns a string derived from this string by replacing every occurrence of oldChar with newChar.

Exception

  • NA

Example

The following example shows the usage of java.lang.String.replace() method.

package com.tutorialspoint;

import java.lang.*;

public class StringDemo {

  public static void main(String[] args) {
  
    String str = "aacdeaa";
    System.out.println("string = " + str);

    // replace all 'a' characters with 'b' characters.
    String replaceStr = str.replace('a', 'b');

    // prints the strings after replacement
    System.out.println("new string = " + replaceStr);
  }
}

Let us compile and run the above program, this will produce the following result:

string = aacdeaa
new string = bbcdebb



Advertisements
Advertisements