StringBuffer deleteCharAt() in Java

deleteCharAt(): This method is available in java.lang.StringBuffer class of Java.

Syntax:

StringBuffer java.lang.StringBuffer.deleteCharAt(int index)

This method takes one argument of type int as its parameter. This method removes the char at the specified position in this sequence.

Note: This sequence is shortened by one char.

Parameters: One parameter is required for this method.

index: Index of char to remove.

Returns: This object.

Throws:

StringIndexOutOfBoundsException - if the index is negative or greater than or equal to length().

For Example:

StringBuffer str = new StringBuffer("Hello World")

int index = 3

str.deleteCharAt(index) = > It returns Helo World.

Approach 1: When the index is in the range.

Java

public class DeleteCharAt {
    public static void main(String[] args) {

        StringBuffer str = new StringBuffer("Hello World");

        int index = 3;
        System.out.println(str.deleteCharAt(index));
    }
}

Output:

Helo World


Approach 2: When the index is out of range.

Java

public class DeleteCharAt {
    public static void main(String[] args) {

        StringBuffer str = new StringBuffer("Hello World");

        int index = -1;
        System.out.println(str.deleteCharAt(index));
    }
}

Output:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: index -1, length 11 at java.base/java.lang.String.checkIndex(String.java:3693) at java.base/java.lang.AbstractStringBuilder.deleteCharAt(AbstractStringBuilder.java:965) at java.base/java.lang.StringBuffer.deleteCharAt(StringBuffer.java:480)


No comments:

Post a Comment