Pages

Tuesday, May 14, 2019

Insert a String into another String in Java

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.

No comments:

Post a Comment

Please do not add any spam links in the comments section.