Inserting Characters in a String Builder – Selected API Classes

Inserting Characters in a String Builder

The overloaded method insert() can be used to insert characters at a given offset in a string builder.

Click here to view code image

StringBuilder insert(int offset, Object obj)
StringBuilder insert(int dstOffset, CharSequence seq)
StringBuilder insert(int dstOffset, CharSequence seq, int start, int end)
StringBuilder insert(int offset, String str)
StringBuilder insert(int offset, char[] charArray)
StringBuilder insert(int offset,
type
 c)

In the methods above, type can be char, boolean, int, long, float, or double. The second argument is converted to a string, if necessary, by applying the static method String.valueOf(). The offset argument specifies where the characters are to be inserted in the string builder, and must be greater than or equal to 0. Note that the offset specifies the number of characters from the start of the string builder.

Replacing Characters in a String Builder

The following methods can be used to replace characters in a string builder:

Click here to view code image

void setCharAt(int index, char ch)

Changes the character at a specified index in the string builder. An IndexOutOfBoundsException is thrown if the index is not valid. This method does not change the length of the string builder, and does not return a value.

Click here to view code image

StringBuilder replace(int start, int end, String replacement)

Replaces the characters in a subsequence of the string builder with the characters in the specified String. The subsequence is defined by the start index (inclusive) and the end index (exclusive). It returns the modified string builder. If the start index is not valid (i.e., start index is negative, greater than length(), or greater than end index.), a StringIndexOutOfBoundsException is thrown.

Deleting Characters in a String Builder

The following methods can be used to delete characters from specific positions in a string builder:

Click here to view code image

StringBuilder deleteCharAt(int index)
StringBuilder delete(int start, int end)

The first method deletes a character at a specified index in the string builder, contracting the string builder by one character. The second method deletes a substring, which is specified by the start index (inclusive) and the end index (exclusive), contracting the string builder accordingly. If start index is equal to end index, no changes are made.

Leave a Reply

Your email address will not be published. Required fields are marked *