Insert a String into Another String in Java



In this article, we will explore how to insert a string into another string at a specific position using Java. To do so we will be using the StringBuffer class

StringBuffer class: StringBuffer class creates and manipulates strings that can be changed. It changes the contents of the string without creating a new object each time.

Problem Statement

Write a program in Java to insert a string into another string ?

Input

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

Steps to insert a string into another string

Following are the steps to insert a string into another string in Java ?

  • First import all the classes from java.lang package.
  • Define the original string and the substring to insert.
  • Determine the index where the new substring should be inserted.
  • We will use the StringBuffer class to modify the original string.
  • Apply the insert() method to place the new substring at the desired index.
  • Output the final result.

Java program to insert a string into another string

Let us now see an example of inserting a string into another ?

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!

Code Explanation

In this example, we start by defining our original string str as "That's good!" and the substring newSub as "no ". We also set the index where the new substring will be inserted, which is 6 in this case. To modify the string, we use the StringBuffer class from the java.lang package, which allows us to create a mutable sequence of characters. We then apply the insert() method of the StringBuffer class to insert the new substring at the specified index, adjusting by +1 to insert after the chosen position. Finally, the modified string is converted back to a string using the toString() method and printed as the output.

Updated on: 2024-08-27T18:46:59+05:30

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements