String Buffer methods in Java

Pubblicato il: 21 agosto 2024
sul canale di: 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.


In questa pagina del sito puoi guardare il video online String Buffer methods in Java della durata di ore minuti seconda in buona qualità , che l'utente ha caricato Engineering Unplugged 21 agosto 2024, condividi il link con amici e conoscenti, su youtube questo video è già stato visto 51 volte e gli è piaciuto 1 spettatori. Buona visione!