Insert a String into another String in Java


Let’s say we have a string “That’s good!” and within that we need to insert the text “no”. Therefore, the resultant string should be “That’s no good!” −

String str = "That's good!";
String newSub = "no ";

Now, the index where the new sub string will get inserted −

int index = 6;

Insert the new substring now −

StringBuffer resString = new StringBuffer(str);
resString.insert(index + 1, newSub);

Let us now see an example to insert a string into another −

Example

 Live Demo

import java.lang.*;
public class Main {
   public static void main(String[] args) {
      String str = "That's good!";
      String newSub = "no ";
      int index = 6;
      System.out.println("Initial String = " + str);
      System.out.println("Index where new string will be inserted = " + index);
      StringBuffer resString = new StringBuffer(str);
      resString.insert(index + 1, newSub);
      System.out.println("Resultant String = "+resString.toString());
   }
}

Output

Initial String = That's good!
Index where new string will be inserted = 6
Resultant String = That's no good!

Updated on: 20-Sep-2019

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements