Replace first occurrence of a character in Java

Java 8Object Oriented ProgrammingProgramming

To replace the first occurrence of a character in Java, use the replaceFirst() method.

Here is our string.

String str = "The Haunting of Hill House!";

Let us replace the first occurrence of character “H”

str.replaceFirst("(?:H)+", "B");

The following is the complete example.

Example

 Live Demo

public class Demo {
    public static void main(String[] args) {
       String str = "The Haunting of Hill House!";
       System.out.println("String: "+str);
       String res = str.replaceFirst("(?:H)+", "B");
       System.out.println("String after replacing a character's first occurrence: "+res);
    }
}

Output

String: The Haunting of Hill House!
String after replacing a character's first occurance: The Baunting of Hill House!
raja
Published on 12-Dec-2018 12:03:07
Advertisements