StringBuilder replace() in Java with Examples

The replace(int start, int end, String str) method of StringBuilder class is used to replace the characters in a substring of this sequence with characters in the specified String. The substring begins at the specified index start and extends to the character at index end – 1 or to the end of the sequence if no such character exists. At first, the characters of substring are removed and the string passed as parameters are inserted in place of those characters.
Syntax:

public StringBuilder replace?(int start, int end, String str)

Parameters:
This method accepts three parameters:

  1. start – Integer type value which refers to the starting index.
  2. end – Integer type value which refers to the ending index.
  3. str – String type value which refer to the String that will replace previous contents.

Returns:
This method returns StringBuilder object after succesful replacement of characters.
Exception:
If the start is negative, greater than length(), or greater than end then StringIndexOutOfBoundsException.

Below programs illustrate the java.lang.StringBuilder.replace() method:
Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to demonstrate
// the replace() Method.
  
class GFG {
    public static void main(String[] args)
    {
  
        // create a StringBuilder object
        // with a String pass as parameter
        StringBuilder str
            = new StringBuilder("WelcomeGeeks");
  
        // print string
        System.out.println("String = "
                           + str.toString());
  
        // replace Character from index 1 to 7 by "e are "
        StringBuilder strReturn = str.replace(1, 7, "e are ");
  
        // print string
        System.out.println("After Replace() String = "
                           + strReturn.toString());
    }
}

chevron_right


Output:

String = WelcomeGeeks
After Replace() String = We are Geeks

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to demonstrate
// the replace() Method.
  
class GFG {
    public static void main(String[] args)
    {
  
        // create a StringBuilder object
        // with a String pass as parameter
        StringBuilder str
            = new StringBuilder("Tony Stark will die");
  
        // print string
        System.out.println("String = "
                           + str.toString());
  
        // replace Character from index 15 to 16 by " not "
        StringBuilder strReturn = str.replace(15, 16, " not ");
  
        // print string
        System.out.println("After Replace() String = "
                           + strReturn.toString());
    }
}

chevron_right


Output:

String = Tony Stark will die
After Replace() String = Tony Stark will not die

Example 3: When negative index is passed:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to demonstrate
// Exception thrown by the replace() Method.
  
class GFG {
    public static void main(String[] args)
    {
  
        // create a StringBuilder object
        // with a String pass as parameter
        StringBuilder str
            = new StringBuilder("Tony Stark");
  
        try {
            // replace Character from index -15 to 16 by "Captain America"
            StringBuilder strReturn = str.replace(-15, 16, "Captain America");
        }
        catch (Exception e) {
  
            e.printStackTrace();
        }
    }
}

chevron_right


Output:

java.lang.StringIndexOutOfBoundsException: String index out of range: -15
    at java.lang.AbstractStringBuilder.replace(AbstractStringBuilder.java:851)
    at java.lang.StringBuilder.replace(StringBuilder.java:262)
    at GFG.main(File.java:17)

Example 4: When start index passed is greater than end index:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to demonstrate
// Exception thrown by the replace() Method.
  
class GFG {
    public static void main(String[] args)
    {
  
        // create a StringBuilder object
        // with a String pass as parameter
        StringBuilder str
            = new StringBuilder("Tony Stark");
  
        try {
            // replace Character from index 5 to 3 by "Captain America"
            StringBuilder strReturn = str.replace(5, 3, "Captain America");
        }
        catch (Exception e) {
  
            e.printStackTrace();
        }
    }
}

chevron_right


Output:

java.lang.StringIndexOutOfBoundsException: start > end
    at java.lang.AbstractStringBuilder.replace(AbstractStringBuilder.java:855)
    at java.lang.StringBuilder.replace(StringBuilder.java:262)
    at GFG.main(File.java:17)

References:
https://docs.oracle.com/javase/10/docs/api/java/lang/StringBuilder.html#replace(int, int, java.lang.String)



My Personal Notes arrow_drop_up

I am a Developer I love to code and bring my ideas alive

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.