Dart StringBuffer by Examples
In this Dart tutorial, we learn how to use StringBuffer class, a class for concatenating strings efficiently in Dart programming language.
How to use StringBuffer class to build a String
In the following example Dart program we use StringBuffer to build a String by using write() method to add String content and then use toString() method to get the final String.
void main() {
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.write("Hello, ");
stringBuffer.write("Mobile");
stringBuffer.write("Code");
stringBuffer.write(".Dev");
print(stringBuffer.toString());
}
Hello, MobileCode.Dev
The writeln() method to write a line of String value.
void main() {
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.writeln("Hello, ");
stringBuffer.writeln("Mobile");
stringBuffer.writeln("Code");
stringBuffer.writeln(".Dev");
print(stringBuffer.toString());
}
Hello,
Mobile
Code
.Dev
The clear() method to clear StringBuffer content.
void main() {
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.write("First ");
stringBuffer.write("String");
print(stringBuffer.toString());
stringBuffer.clear();
stringBuffer.write("Second ");
stringBuffer.write("String");
print(stringBuffer.toString());
stringBuffer.clear();
stringBuffer.write("Third ");
stringBuffer.write("String");
print(stringBuffer.toString());
}
First String
Second String
Third String
Check a StringBuffer is empty or not
Using isEmpty property.
void main() {
StringBuffer stringBuffer = new StringBuffer();
if(stringBuffer.isEmpty) {
print("StringBuffer is empty");
} else {
print("StringBuffer is not empty");
}
}
StringBuffer is empty
void main() {
StringBuffer stringBuffer = new StringBuffer("mobilecode.dev");
if(stringBuffer.isEmpty) {
print("StringBuffer is empty");
} else {
print("StringBuffer is not empty");
}
}
StringBuffer is not empty
Using isNotEmpty property.
void main() {
StringBuffer stringBuffer = new StringBuffer();
if(stringBuffer.isNotEmpty) {
print("StringBuffer is not empty");
} else {
print("StringBuffer is empty");
}
}
StringBuffer is empty
void main() {
StringBuffer stringBuffer = new StringBuffer("mobilecode.dev");
if(stringBuffer.isNotEmpty) {
print("StringBuffer is not empty");
} else {
print("StringBuffer is empty");
}
}
StringBuffer is not empty
Happy Coding 😊
Related Articles
Dart String Data Type by Examples
Dart integer Data Type by Examples
Dart double Data Type by Examples
Dart bool Data Type by Examples