Introduction to String Replace() Function In Java

Introduction to String Replace() Function In Java

Java string replace method returns the string replacing all the old char or CharSequence to a new char or CharSequence. At times, it is required to replace some characters in a String with a new character. It might also be required to change an entire sequence of characters with a new sequence of characters, i.e., replacing an old CharSequence with a new CharSequence. The java.lang.String.replace() method is a built-in method of the String class designed just for this purpose.

Java String replace

Java string replace() method returns the new string resulting from replacing all occurrences of old characters in the string with new characters.

See the following figure. ![This is image title](https://appdividend.com/wp-content/uploads/2019/10/Java-String-replace-Example.png "This is image title

Syntax

public String replace(char old, char new),

Where old is the character to be replaced and new is the character to be inserted in its place.

It returns a string by replacing every occurrence of old with new.

Internal Implementation

public String replace(char oldChar, char newChar) {
    if (oldChar != newChar) {
      int len = value.length;
      int i = -1;
      char[] val = value; /* avoid getfield opcode */

      while (++i < len) {
        if (val[i] == oldChar) {
          break;
        }
      }
      if (i < len) {
        char buf[] = new char[len];
        for (int j = 0; j < i; j++) {
          buf[j] = val[j];
        }
        while (i < len) {
          char c = val[i];
          buf[i] = (c == oldChar) ? newChar : c;
          i++;
        }
        return new String(buf, true);
      }
    }
    return this;
  }

Example1.java:

The following example demonstrates how the replace() method is used to change all occurrences of an old character with a new character.

public class Example1 {
  public static void main(String[] args) {
    System.out.println("This program will replace all occurences of 's' with 'z'");
    String s = new String("This is a demo string. This is s.");

    System.out.println(s);
    String s_new = new String();
    s_new = s.replace('s', 'z');

    System.out.println(s_new);

  }
}

Output

This program will replace all occurrences of ‘s’ with ‘z’
This is a demo string. This is s.
Thiz iz a demo ztring. Thiz iz z.

Here, java replace() method is used to replace all occurrences of the old character ‘s,’ replaced with the new character ‘z’.

Example2.java

Since JDK 1.5, Java also allows replacing an entire CharSequence with a new one. The following example demonstrates such a case:

public class Example2 {
  public static void main(String[] args) {
    String s = new String("He decided to go to New York.");
    System.out.println(s);

    String s2 = new String();
    s2 = s.replace("New York", "Moscow");
    System.out.println(s2);
  }
}

Output

He decided to go to New York.
He decided to go to Moscow.

Here, the sequence “New York” gets replaced with “Moscow”. Multiple occurrences of a sequence can be replaced in the same way. The same is demonstrated in the next example.

Example3.java

public class Example3 {
  public static void main(String[] args) {
    String s = new String("I had a bike. But I sold the bike to get a new bike.");
    System.out.println(s);

    String s2 = new String();
    s2 = s.replace("bike", "car");
    System.out.println(s2);
  }
}

See the output.

I had a bike. But I sold the bike to get a new bike.
I had a car. But I sold the car to get a new car.

Here, all occurrences of “bike” are replaced with “car” by using the** replace()** method.

In conclusion, the** java.lang.String.replace() **method is used to replace all the occurrences of a character/sequence of characters with a new character/sequence of characters.

Finally, String replace() Function In Java Tutorial is over.

Thanks for reading !

java programming

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

How to Install OpenJDK 11 on CentOS 8

What is OpenJDK? OpenJDk or Open Java Development Kit is a free, open-source framework of the Java Platform, Standard Edition (or Java SE).

Java Core (2020) | Java for beginners | Brush up your Java Skills | Get Hired

In this video we will learn about all the major concepts that come under Java Core . The course is very carefully designed and is made with keeping simplicit...

Learn Java Programming | Java Complete Tutorial for Beginners | Simpliv

This program on Java programing from Simpliv’s experts uses Java and an Integrated Development Environment (IDE). Just download this, with their help of course, and open your way to hundreds of lines of source code, and hundreds of lines of comments. That is some Java programming learning!

A Game to Boost Your Java Object Oriented Programming Skills

This is a simple black screen console game where first the program will automatically generate a random number, and all the players who play the game here will continue to guess the number one by one and match it with the previous program.

Introduction To Java In Hindi | Learn Java Programming | Java Basics

Introduction To Java In Hindi | Learn Java Programming | Java Basics. This article Session on Introduction to Java in Hindi will cover the 'what, why, and how' of Java. This will include features, data types, operators, conditional statements, and loops.