Replacing Substrings in a Java String

Java 8Object Oriented ProgrammingProgramming

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

 Live Demo

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!
raja
Published on 06-Dec-2018 16:39:38
Advertisements