- 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
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!
- Related Articles
- Java Program to replace all occurrences of given String with new one
- Java Program to replace all occurrences of a given character with new character
- Java Program to replace all occurrences of a given character in a string
- Replace All Occurrences of a Python Substring with a New String?
- Python Program to Replace all Occurrences of ‘a’ with $ in a String
- How to replace all occurrences of a string with another string in Python?
- C++ program to replace all occurrences of string AB with C without using extra space
- Replace one string with another string with Java Regular Expressions
- How to replace all occurrences of a word in a string with another word in java?
- Java Program to replace one specific character with another
- Replace all occurrences of specified element of ArrayList with Java Collections
- How to replace all occurrences of a string in JavaScript?
- Remove new lines from a string and replace with one empty space PHP?
- Java program to count occurrences of a word in string
- C program to replace all zeros with one in a given integer.

Advertisements