Java insert string value

Class StringBuilder

A mutable sequence of characters. This class provides an API compatible with StringBuffer , but with no guarantee of synchronization. This class is designed for use as a drop-in replacement for StringBuffer in places where the string buffer was being used by a single thread (as is generally the case). Where possible, it is recommended that this class be used in preference to StringBuffer as it will be faster under most implementations.

The principal operations on a StringBuilder are the append and insert methods, which are overloaded so as to accept data of any type. Each effectively converts a given datum to a string and then appends or inserts the characters of that string to the string builder. The append method always adds these characters at the end of the builder; the insert method adds the characters at a specified point.

For example, if z refers to a string builder object whose current contents are » start «, then the method call z.append(«le») would cause the string builder to contain » startle «, whereas z.insert(4, «le») would alter the string builder to contain » starlet «.

In general, if sb refers to an instance of a StringBuilder , then sb.append(x) has the same effect as sb.insert(sb.length(), x) .

Every string builder has a capacity. As long as the length of the character sequence contained in the string builder does not exceed the capacity, it is not necessary to allocate a new internal buffer. If the internal buffer overflows, it is automatically made larger.

Читайте также:  Css border spacing 2px

Instances of StringBuilder are not safe for use by multiple threads. If such synchronization is required then it is recommended that StringBuffer be used.

Unless otherwise noted, passing a null argument to a constructor or method in this class will cause a NullPointerException to be thrown.

Источник

Insert a String into another String in Java

Twitter Facebook Google Pinterest

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.

Input: OriginalStringValue = "java blog" newStringToBeinserted = " w3schools" position = 4 Output: java w3schools blog
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 .

Читайте также:  Background color coding in html

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.

Читайте также:  Php array diff многомерный массив

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)

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)

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.

Источник

Оцените статью