Dart StringBuffer()
Syntax & Examples
StringBuffer constructor
The `StringBuffer` constructor in Dart creates a string buffer with an initial content.
Syntax of StringBuffer
The syntax of StringBuffer.StringBuffer constructor is:
StringBuffer([Object content = "" ])
This StringBuffer constructor of StringBuffer creates the string buffer with an initial content.
Parameters
Parameter | Optional/Required | Description |
---|---|---|
|
✐ Examples
1 Creating a StringBuffer with initial content
In this example,
- We create a `StringBuffer` named `buffer` with the initial content 'Initial content'.
- We convert the buffer to a string using `toString()` and print it to standard output.
Dart Program
void main() {
StringBuffer buffer = StringBuffer('Initial content');
print(buffer.toString());
}
Output
Initial content
2 Appending elements to a StringBuffer using writeAll()
In this example,
- We create a `StringBuffer` named `buffer` without any initial content.
- We use the `writeAll()` method to append a list of strings to the buffer.
- We convert the buffer to a string using `toString()` and print it to standard output.
Dart Program
void main() {
StringBuffer buffer = StringBuffer();
buffer.writeAll(['This', ' is', ' a', ' string', ' buffer']);
print(buffer.toString());
}
Output
This is a string buffer
3 Appending elements to a StringBuffer using write()
In this example,
- We create a `StringBuffer` named `buffer` without any initial content.
- We use the `write()` method twice to append 'Hello' and ' World' to the buffer.
- We convert the buffer to a string using `toString()` and print it to standard output.
Dart Program
void main() {
StringBuffer buffer = StringBuffer();
buffer.write('Hello');
buffer.write(' World');
print(buffer.toString());
}
Output
Hello World
Summary
In this Dart tutorial, we learned about StringBuffer constructor of StringBuffer: the syntax and few working examples with output and detailed explanation for each example.