String Buffer methods in Java

Publié le: 21 août 2024
sur la chaîne: Engineering Unplugged
51
1

The `StringBuffer` class in Java is used to create mutable (modifiable) strings. Here are some commonly used methods with examples:

1. append(String str)
Adds the specified string to the end of the buffer.
Example:
StringBuffer sb = new StringBuffer("Hello");
sb.append(" World");
System.out.println(sb); // Output: Hello World

2. insert(int offset, String str)
Inserts the string at the specified position.
Example:
StringBuffer sb = new StringBuffer("Hello");
sb.insert(5, " World");
System.out.println(sb); // Output: Hello World

3. replace(int start, int end, String str)
Description: Replaces characters from `start` to `end` with the specified string.
Example:
StringBuffer sb = new StringBuffer("Hello World");
sb.replace(6, 11, "Java");
System.out.println(sb); // Output: Hello Java

4. delete(int start, int end)
Removes characters from `start` to `end`.
Example:
StringBuffer sb = new StringBuffer("Hello World");
sb.delete(5, 11);
System.out.println(sb); // Output: Hello

5. reverse()
Reverses the characters in the buffer.
Example:
StringBuffer sb = new StringBuffer("Hello");
sb.reverse();
System.out.println(sb); // Output: olleH

6. capacity()
Returns the current capacity of the buffer.
Example:
StringBuffer sb = new StringBuffer();
System.out.println(sb.capacity()); // Output: 16 (default capacity)

These methods demonstrate how `StringBuffer` can be used for efficient string manipulation.


Sur cette page du site, vous pouvez voir la vidéo en ligne String Buffer methods in Java durée heure minute seconde en bonne qualité , qui a été Téléchargé par l'utilisateur Engineering Unplugged 21 août 2024, Partagez le lien avec vos amis et connaissances, sur youtube cette vidéo a déjà été regardée 51 fois et il a aimé 1 téléspectateurs. Bon visionnage!