Skip to content
Related Articles

Related Articles

Improve Article

StringBuilder replace() in Java with Examples

  • Last Updated : 10 Dec, 2019

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 successful 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:




// 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());
    }
}

Output:



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

Example 2:




// 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());
    }
}

Output:

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

Example 3: When negative index is passed:




// 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();
        }
    }
}

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:




// 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();
        }
    }
}

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)

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.




My Personal Notes arrow_drop_up
Recommended Articles
Page :