Dart StringBuffer clear()
Syntax & Examples


StringBuffer.clear() method

The `clear` method in Dart clears the string buffer.


Syntax of StringBuffer.clear()

The syntax of StringBuffer.clear() method is:

 void clear() 

This clear() method of StringBuffer clears the string buffer.

Return Type

StringBuffer.clear() returns value of type void.



✐ Examples

1 Clearing a StringBuffer with content

In this example,

  1. We create a `StringBuffer` named `buffer` with the content 'Example'.
  2. We print the buffer before clearing.
  3. We call the `clear()` method to clear the buffer.
  4. We print the buffer after clearing, which should show an empty buffer.

Dart Program

void main() {
  StringBuffer buffer = StringBuffer('Example');
  print('Before clearing: $buffer');
  buffer.clear();
  print('After clearing: $buffer');
}

Output

Before clearing: Example
After clearing: 

2 Clearing a StringBuffer with longer content

In this example,

  1. We create a `StringBuffer` named `buffer` with the content 'Another Example'.
  2. We print the buffer before clearing.
  3. We call the `clear()` method to clear the buffer.
  4. We print the buffer after clearing, which should show an empty buffer.

Dart Program

void main() {
  StringBuffer buffer = StringBuffer('Another Example');
  print('Before clearing: $buffer');
  buffer.clear();
  print('After clearing: $buffer');
}

Output

Before clearing: Another Example
After clearing: 

3 Clearing a StringBuffer with more content

In this example,

  1. We create a `StringBuffer` named `buffer` with the content 'Yet Another Example'.
  2. We print the buffer before clearing.
  3. We call the `clear()` method to clear the buffer.
  4. We print the buffer after clearing, which should show an empty buffer.

Dart Program

void main() {
  StringBuffer buffer = StringBuffer('Yet Another Example');
  print('Before clearing: $buffer');
  buffer.clear();
  print('After clearing: $buffer');
}

Output

Before clearing: Yet Another Example
After clearing: 

Summary

In this Dart tutorial, we learned about clear() method of StringBuffer: the syntax and few working examples with output and detailed explanation for each example.