Menu
Topics Index
...
`


Strings > StringBuffer >
Siva Nookala - 06 Oct 2016
The methods delete and deleteCharAt are used for deleting a character or a sequence of characters with in a StringBuffer.

The Syntax for delete is:
StringBuffer delete(int startIndex, int endIndex)
This method is used for deleting a sequence of characters within a StringBuffer. Here startIndex specifies the starting index of character which you want to delete and endIndex specifies an index one past the last character to remove. This method deletes the substring from startIndex to endIndex - 1 and the resulting StringBuffer object is returned.

The method for deleteCharAt is:
StringBuffer deleteCharAt(int loc)
This method is used to delete a single character at an index (loc). The resulting StringBuffer object is returned.

Here is the example program to demonstrate delete, deleteCharAt:
StringBufferdelete and deleteCharAt Demo
class StringBufferDeleteExample
{
    public static void main(String arg[])
    {
        StringBuffer firstWord = new StringBuffer("Bharat");
        System.out.println(firstWord);
        firstWord.delete(1, 4);
        System.out.println(firstWord);
        firstWord.deleteCharAt(0);
        System.out.println(firstWord);    
    }
}
OUTPUT

Bharat
Bat
at

DESCRIPTION

This program shows how to delete a character or set of characters from a StringBuffer object. The first output line Bharat is just the display of contents of firstWord. The second output line Bat is obtained by deleting a substring from Bharat using delete(startIndex, endIndex). The substring(1, 4) i.e har is deleted from Bharat to get Bat. The third output at is obtained by deleting the first character of Bat using deleteCharAt(0). The character at zero position is deleted.

THINGS TO TRY
  • Write this code at the end of above program and observe the output. The output is should be a. Since characters from 1 are deleted
    firstWord.delete(1, 4);</br>
    System.out.println(firstWord);

Dependent Topics : Java substring  Java charAt() And setCharAt() Methods in StringBuffer  Java append() Method In StringBuffer  Java setLength() Method In StringBuffer Class 

0
Wrong
Score more than 2 points

© meritcampus 2019

All Rights Reserved.

Open In App