
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
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!
Advertisements