Replace first occurrence of a character in Java



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!
Updated on: 2020-06-26T14:40:01+05:30

8K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements