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

Java 8Object Oriented ProgrammingProgramming

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!
raja
Published on 06-Dec-2018 16:43:56
Advertisements