Programming Tutorials

delete() and deleteCharAt() in Java

By: Ivan Lim in Java Tutorials on 2007-09-12  

Java 2 adds to StringBuffer the ability to delete characters using the methods delete() and deleteCharAt(). These methods are shown here:

StringBuffer delete(int startIndex, int endIndex)
StringBuffer deleteCharAt(int loc)

The delete() method deletes a sequence of characters from the invoking object. Here,startIndex specifies the index of the first character to remove, and endIndex specifies an index one past the last character to remove. Thus, the substring deleted runs from startIndex to endIndex-1. The resulting StringBufferobject is returned.

The deleteCharAt() method deletes the character at the index specified by loc. It returns the resulting StringBuffer object.

Here is a program that demonstrates the delete() and deleteCharAt() methods:

// Demonstrate delete() and deleteCharAt()
class deleteDemo {
    public static void main(String args[]) {
        StringBuffer sb = new StringBuffer("This is a test.");
        sb.delete(4, 7);
        System.out.println("After delete: " + sb);
        sb.deleteCharAt(0);
        System.out.println("After deleteCharAt: " + sb);
    }
}

The following output is produced:

After delete: This a test.
After deleteCharAt: his a test.





Add Comment

* Required information
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in Java )

Latest Articles (in Java)