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");
        firstWord.delete(1, 4);



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.

  • 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>

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

Score more than 2 points

© meritcampus 2016 - 2017

All Rights Reserved.