replace(): This method is available in java.lang.StringBuilder class of Java.
Syntax:
StringBuilder java.lang.StringBuilder.replace(int start, int end, String str)
This method takes three arguments, two are of type int and one of type String as its parameters. This method replaces the characters in a substring of this sequence with characters in the specified String. The substring begins at the specified start and extends to the character at index end - 1 or to the end of the sequence if no such character exists.
Note: First the characters in the substring are removed and then the specified String is inserted at the start.
Parameters: Three parameters are required for this method.
start: The beginning index, inclusive.
end: The ending index, exclusive.
str: String that will replace previous contents.
Returns: This object.
Throws:
StringIndexOutOfBoundsException - if start is negative, greater than length(), or greater than end.
For Example:
StringBuilder str = new StringBuilder("Hello World")
int start = 2, end = 7
String str1 = "ABCABC"
str.replace(start,end,str1) = > It returns HeABCABCorld.
Approach 1: When the index is in the range.
Java
public class Replace {public static void main(String[] args) {StringBuilder str = new StringBuilder("Hello World");int start = 2, end = 7;String str1 = "ABCABC";System.out.println(str.replace(start, end, str1));}}
Output:
HeABCABCorld
Approach 2: When the index is out of range.
Java
public class Replace {public static void main(String[] args) {StringBuilder str = new StringBuilder("Hello World");int start = 10, end = 7;String str1 = "ABCABC";System.out.println(str.replace(start, end, str1));}}
Output:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: start 10, end 7, length 11 at java.base/java.lang.AbstractStringBuilder.checkRangeSIOOBE(AbstractStringBuilder.java:1802) at java.base/java.lang.AbstractStringBuilder.replace(AbstractStringBuilder.java:995) at java.base/java.lang.StringBuilder.replace(StringBuilder.java:301)
No comments:
Post a Comment