- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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!
- Related Articles
- Perform search/replace for only the first occurrence of a character in MySQL table records?
- Perform search/replace for only the first occurrence of a character with session variable in MySQL
- C program to replace all occurrence of a character in a string
- String function to replace nth occurrence of a character in a string JavaScript
- Finding the last occurrence of a character in a String in Java
- Replace Character in a String in Java without using replace() method
- Java program to check occurrence of each character in String
- Get the index of the first occurrence of a separator in Java
- Get the substring after the first occurrence of a separator in Java
- Java Program to replace all occurrences of a given character with new character
- Java program to count the occurrence of each character in a string using Hashmap
- Python - Replace duplicate Occurrence in String
- Java Program to replace all occurrences of a given character in a string
- Java Program to Replace a Character at a Specific Index
- First occurrence of True number in Python

Advertisements