Hello Folks,

As part of Frequently Asked Java Programs In Interviews For Freshers And Experienced, in this post we will see a java program to Insert a String into Another String at given index.

Problem Statement:-

String s1 = MakeEasy

String s2= Selenium

indexToInsertS2= 4

Insert s2 in to s1 at index 4th. So s1 should be “MakeSeleniumEasy”.

Solution:-

We will see three approaches to solve this because interviewer may ask you not to use readymade methods.

Approach 1:-

Using StringBuilder or StringBuffer class:

There is a method called insert() in both classes which you can use to insert a string at given index.

Java Program:-

Output:-

String s1 before inserting s2 at index 4: MakeEasy
String s1 after inserting s2 at index 4: MakeSeleniumEasy

Approach 2:-

Using substring() method:-

We need to divide and concat strings. This approach will have two steps:-

  1. Divide string S1 in to two parts. First part will start from first index i.e zero till index to insert String s2 minus 1. Second part will be from index to insert String s2 till last.

E.g. “MakeEasy” will be divided into two parts:- (0,3) and (4,7) i.e. “Make” & “Easy”.

We will use substring() method for the same. Since substring() method excludes provided last index so no need to do minus 1.

2. Concat String s2 in between two parts:- part1+s2+part2.

Java Program:-

Output:-

String s1 before inserting s2 at index 4: MakeEasy
String s1 after inserting s2 at index 4: MakeSeleniumEasy

Approach 3:

Using loop:-

We need to iterate s1 char by char by index. Concatenate char by char till iterating index is same as index to insert string s2 i.e. indexToInsertS2 . Once both are same, Concatenate whole s2 with concatenated string followed by current indexed char of s1. Continue the for loop to Concatenate remaining chars of String s1.

Java Program:-

Output:-

String s1 before inserting s2 at index 4: MakeEasy
String s1 after inserting s2 at index 4: MakeSeleniumEasy

#HappyCoding

Author: Amod Mahajan

My name is Amod Mahajan and I am an IT employee with 6+ years of experience in Software testing and staying in Bengaluru. My area of interest is Automation testing. I started from basics and went through so many selenium tutorials. Thanks to Mukesh Otwani as his tutorials are easy and cover basics to advance. I have habit of exploring concepts by deep diving. I used to make notes. I thought of sharing my knowledge through posts and now I am here. #KeepLearning #ShareLearning

Leave a Reply