insert(): This method is available in java.lang.StringBuilder class of Java.
Syntax:
StringBuilder java.lang.StringBuilder.insert(int dstOffset, CharSequence s, int start, int end)
This method takes four arguments, one of type CharSequence and the other three are of type int as its parameters. This method inserts a subsequence of the specified CharSequence into this sequence. The subsequence of the argument s specified by start and end is inserted,in order, into this sequence at the specified destination offset.
Note:
1. The length of this sequence is increased by the end - start.
2. The dstOffset argument must be greater than or equal to 0, and less than or equal to the length of this sequence.
3. The start argument must be nonnegative, and not greater than the end.
4. The end argument must be greater than or equal to start, and less than or equal to the length of s.
5. If s is null, then this method inserts characters as if the s parameter was a sequence containing the four characters "null".
Parameters: Four parameters are required for this method.
dstOffset: the offset in this sequence.
s: the sequence to be inserted.
start: the starting index of the subsequence to be inserted.
end: the end index of the subsequence to be inserted.
Returns: a reference to this object.
Throws:
StringIndexOutOfBoundsException - if dstOffsetis negative or greater than this.length(), or start or end are negative, or start is greater than end or end is greater than s.length()
Approach 1: When the index is in the range.
Java
public class InsertStringBuilderCharSequence {public static void main(String[] args) {StringBuilder str = new StringBuilder("Hello World");// insert CharSequence Rangeint dstOffset = 2;CharSequence s = "YYYYYYY";int start = 2, end = 5;str.insert(dstOffset, s, start, end);System.out.println(str);}}
Output:
HeYYYllo World
Approach 2: When the index is out of range.
Java
public class InsertStringBuilderCharSequence {public static void main(String[] args) {StringBuilder str = new StringBuilder("Hello World");// insert CharSequence Rangeint dstOffset = -1;CharSequence s = "YYYYYYY";int start = 2, end = 5;str.insert(dstOffset, s, start, end);System.out.println(str);}}
Output:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: offset -1, length 11 at java.base/java.lang.String.checkOffset(String.java:3704) at java.base/java.lang.AbstractStringBuilder.insert(AbstractStringBuilder.java:1293) at java.base/java.lang.StringBuilder.insert(StringBuilder.java:359)
No comments:
Post a Comment