
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
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!
Advertisements