Java Program to replace only first occurrences of given String with new one


Use the replaceFirst() method to replace only first occurrences of given String with new one.

Let’s say we have the following string.

String str = "THIS IS DEMO TEXT!";

We have to replace the first occurrence of “IS” with “EV”. For that, use replaceFirst() method.

str.replaceFirst("IS", "EV");

The following is the final example, wherein the first occurrence of “IS” is replaced.

Example

 Live Demo

public class Demo {
   public static void main(String[] args) {
      String str = "THIS IS DEMO TEXT!";
      System.out.println("String = "+str);
      System.out.println("Replacing only the first occurrence of substring IS...");
      System.out.println("Updated string = "+str.replaceFirst("IS", "EV"));
   }
}

Output

String = THIS IS DEMO TEXT!
Replacing only the first occurrence of substring IS...
Updated string = THEV IS DEMO TEXT!

Updated on: 25-Jun-2020

203 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements