![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
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
Java Program to replace only first occurrences of given String with new one
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
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!
Advertisements