$show=/label

Insert a String into another String in Java

SHARE:

A quick explanation for Java program to Insert a String into another String. Writing program in 3 ways using normal approach, String API and StringBuffer API.

1. Overview

We'll demonstrate how to add a string into another string at any given position in java.

We will write implementation in 3 ways which iterate through the string till given position and then add new string, finally add the remaining original string.

As we know String class is immutable in java. Any operation on string will result a new String.

Insert a String into another String



First, We will see a few example input and outputs.

Example 1:

Input: OriginalStringValue = "java blog"
    newStringToBeinserted = " w3schools"
    position = 4

Output: java w3schools blog

Example 2:

Example 2:
Input: OriginalStringValue = "first last"
    newStringToBeinserted = " middle"
    position = 5

Output: first middle last

We further in this article will discuss on simple approach, using substring method and StringBuffer api.

2. Simple Approach


In this program, We will be using very simple and straight forward approach to solve the problem. Explained step by step below.

2.1 Steps:


a) Initiate startIndex = 0 and endIndex to originalString.length
b) Create a newString with empty content.
c) Iterate the loop through originalString string from originalString to endIndex .
d) Take char by char and add it to newString. Increment startIndex by 1 for each character.
e) If startIndex is equal to position then append the toBeInserted string to the newString.
f) Add rest of the characters to newString.
g) return newString.

2.2 Program

Let us have a look at the following program using substring method.

/**
 * Insert a String into another String in Java using normal approach
 * 
 * @param originalString
 * @param position
 * @param toBeInserted
 * @return
 */
public String insertStringAtPosition(String originalString, int position, String toBeInserted) {

  int startIndex = 0;
  int endIndex = originalString.length();
  String newString = "";

  for (int i = startIndex; i < endIndex; i++) {
  // Insert the original string character into the new string
  newString += originalString.charAt(startIndex);

  if (startIndex == position) {
   // Insert the string to be inserted into the new string
   newString += toBeInserted;
  }
 }

 return newString;
}

3. Using String class substring


String class has a method called substring that returns a part of string for the any given from and to indexes. substring method is overloaded in String class as follows.

substring (int beginIndex): Returns a string that is a substring of this string. The substring begins with the character at the specified index and extends to the end of this string.

substring​(int beginIndex, int endIndex): Returns a string that is a substring of this string. The substring begins at the specified beginIndex and extends to the character at index endIndex - 1. Thus the length of the substring is endIndex-beginIndex.

Note: Always substring method ignores endIndex. Considers 0 to endIndex-1 as substring.

3.1 Steps:


a) Taking three string variables named "first", "middle" and "last".
b) Take substring from originalString from index o to position + 1. Store in "first" string variable.
c) Next store toBeInserted value into "middle" string variable.
d) Take substring from originalString from index position + 1 to it's length.
e) Now concatenating these three strings will give us the final output.

3.2 Program

Let us have a look at the following program using substring method.

/**
 * Insert a String into another String in Java using String class substring
 * method.
 * 
 * @param originalString
 * @param position
 * @param toBeInserted
 * @return
 */
public String insertStringAtPositionUsingSubString(String originalString, int position,
  String toBeInserted) {

 String first = originalString.substring(0, position + 1);
 String middle = toBeInserted;
 String last = originalString.substring(position + 1, originalString.length());
 
 String newString = first + middle + last;

 return newString;
}

4. StringBuffer insert() method


StringBuffer has a method insert() which takes index and string to be inserted. This method will insert the given string at the given position. All rest of the characters right side to it will be shifted to right.

4.1 Steps


a) Create a new StringBuffer instance passing originalString.
b) Call StringBuffer insert method passing index "position + 1" and string toBeInserted.
c) Convert StringBuffer to String by invoking toString() method. This is will be the our output newString.

4.2 Program


Let us have a look at the following program using StringBuffer insert method with offset and string toBeInserted.

/**
 * Insert a String into another String in Java using StringBuffer class insert
 * method.insert method takes offset value which is the index where the new
 * string to be inserted and the string toBeInserted.
 * 
 * @param originalString
 * @param position
 * @param toBeInserted
 * @return
 */
public static String insertStringAtPositionUsingStringBuffer(String originalString, int position,
  String toBeInserted) {

 StringBuffer buffer = new StringBuffer(originalString);
 buffer.insert(position + 1, toBeInserted);
 String newString = buffer.toString();

 return newString;
}


5. Conclusion


In this article, We've discussed about inserting a string into another string using common approcach, stirng substring method and StringBuffer.insert() method.

But, performance wise first approach is a bit time consuming time. substring and insert method does good in performance because these are builtin api methods which are tested by millions lines of code in production.

All code shown in this tutorial are on GitHub.

COMMENTS

BLOGGER

About Us

Author: Venkatesh - I love to learn and share the technical stuff.
Name

accumulo,1,ActiveMQ,2,Adsense,1,API,37,ArrayList,18,Arrays,24,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,8,Collections,37,Collector,1,Command Line,1,Comparator,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,6,Core Java,149,Corona India,1,Create,2,CSS,1,Date,3,Date Time API,38,Dictionary,1,Difference,2,Download,1,Eclipse,3,Efficiently,1,Error,1,Errors,1,Exceptions,8,Fast,1,Files,17,Float,1,Font,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,9,Grant,1,Grep,1,HashMap,2,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Installation,1,Interview Questions,6,Iterate,2,Jackson API,3,Java,32,Java 10,1,Java 11,6,Java 12,5,Java 13,2,Java 14,2,Java 8,128,Java 8 Difference,2,Java 8 Stream Conversions,4,java 8 Stream Examples,12,Java 9,1,Java Conversions,14,Java Design Patterns,1,Java Files,1,Java Program,3,Java Programs,114,Java Spark,1,java.lang,4,java.util. function,1,JavaScript,1,jQuery,1,Kotlin,11,Kotlin Conversions,6,Kotlin Programs,10,Lambda,2,lang,29,Leap Year,1,live updates,1,LocalDate,1,Logging,1,Mac OS,3,Math,1,Matrix,6,Maven,1,Method References,1,Mockito,1,MongoDB,3,New Features,1,Operations,1,Optional,6,Oracle,5,Oracle 18C,1,Partition,1,Patterns,1,Programs,1,Property,1,Python,2,Quarkus,1,Read,1,Real Time,1,Recursion,2,Remove,2,Rest API,1,Schedules,1,Serialization,1,Servlet,2,Sort,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Streams,31,String,61,String Programs,28,String Revese,1,StringBuilder,1,Swing,1,System,1,Tags,1,Threads,11,Tomcat,1,Tomcat 8,1,Troubleshoot,26,Unix,3,Updates,3,util,5,While Loop,1,
ltr
item
JavaProgramTo.com: Insert a String into another String in Java
Insert a String into another String in Java
A quick explanation for Java program to Insert a String into another String. Writing program in 3 ways using normal approach, String API and StringBuffer API.
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj1vFhOmIhVVF4uhfZDx3UkZTlq2ozPxuFrRRmZhty2CV0-z96ZLrbg5_k1FaO_JaYi0kmN0QP74NAU0-KO0rrBMLNGP6fODSsvEAr_uI3N_Itc8xFwk8wBn8V22xFcP9B65iA0iJyTl3U/s400/Insert+a+String+into+another+String.PNG
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj1vFhOmIhVVF4uhfZDx3UkZTlq2ozPxuFrRRmZhty2CV0-z96ZLrbg5_k1FaO_JaYi0kmN0QP74NAU0-KO0rrBMLNGP6fODSsvEAr_uI3N_Itc8xFwk8wBn8V22xFcP9B65iA0iJyTl3U/s72-c/Insert+a+String+into+another+String.PNG
JavaProgramTo.com
https://www.javaprogramto.com/2019/05/insert-string-into-another-string.html
https://www.javaprogramto.com/
https://www.javaprogramto.com/
https://www.javaprogramto.com/2019/05/insert-string-into-another-string.html
true
3124782013468838591
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS PREMIUM CONTENT IS LOCKED STEP 1: Share to a social network STEP 2: Click the link on your social network Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy Table of Content