- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
Replacing Substrings in a Java String
Let’s say the following is our string.
String str = "The Walking Dead!";
We want to replace the substring “Dead” with “Alive”. For that, let us use the following logic. Here, we have used a while loop and within that found the index of the substring to be replaced. In this way, one by one we have replaced the entire substring.
int beginning = 0, index = 0; StringBuffer strBuffer = new StringBuffer(); while ((index = str.indexOf(subStr1, beginning)) >= 0) { strBuffer.append(str.substring(beginning, index)); strBuffer.append(subStr2); beginning = index + subStr1.length(); }
The following is the complete example to replace substrings.
Example
public class Demo { public static void main(String[] args) { String str = "The Walking Dead!"; System.out.println("String: "+str); String subStr1 = "Dead"; String subStr2 = "Alive"; int beginning = 0, index = 0; StringBuffer strBuffer = new StringBuffer(); while ((index = str.indexOf(subStr1, beginning)) >= 0) { strBuffer.append(str.substring(beginning, index)); strBuffer.append(subStr2); beginning = index + subStr1.length(); } strBuffer.append(str.substring(beginning)); System.out.println("String after replacing substring "+subStr1+" with "+ subStr2 +" = "+strBuffer.toString()); } }
Output
String: The Walking Dead! String after replacing substring Dead with Alive = The Walking Alive!
- Related Articles
- Replacing upperCase and LowerCase in a string - JavaScript
- Replacing dots with dashes in a string using JavaScript
- Segregating a string into substrings - JavaScript
- Find all substrings in a string using C#
- Replacing every nth instance of characters in a string - JavaScript
- Update a column value, replacing part of a string in MySQL?
- C# Program to find all substrings in a string
- Get all substrings of a string in JavaScript recursively
- Unique Substrings in Wraparound String in C++
- Unique substrings in circular string in JavaScript
- Replacing vowels with their 1-based index in a string in JavaScript
- Adding paragraph tag to substrings within a string in JavaScript
- Is the string a combination of repeated substrings in JavaScript
- Replacing all special characters with their ASCII value in a string - JavaScript
- Counting even decimal value substrings in a binary string in C++

Advertisements