CodeBlanks Logo Icon CodeBlanks

StringBuffer

Learn efficient string concatenation with StringBuffer.

StringBuffer

Joining many strings with + creates a new string each time, so it is slow in loops. StringBuffer builds a mutable string that grows in place. You write to it and at the end call toString() for the final string. The difference is large when you join hundreds of pieces in a loop.

Example: final sb = StringBuffer(); sb.write("a"); sb.write("b"); print(sb.toString());. writeln adds a newline after each piece. clear empties it. isEmpty tells you if it has content. Ideal for accumulation tasks.

Practice Your turn: build with StringBuffer

Create a StringBuffer and use a for loop to add the numbers 0 through 2 separated by commas. Get the result with toString() and print it.

Starter code

main.dart
void main() {
  // Create a StringBuffer
  // Loop 0,1,2 with commas
  // Print with toString()
}

Sample solution

main.dart
void main() {
  final sb = StringBuffer();
  for (var i = 0; i < 3; i++) {
    if (i > 0) sb.write(",");
    sb.write(i.toString());
  }
  print(sb.toString());
}

Expected output

0,1,2

write and writeln

write appends a single piece; writeln also adds a newline character after each call. If you are building a log file and want each entry on its own line you use writeln. writeAll takes a list and writes each element separated by a delimiter you choose; similar to join but into a StringBuffer.

To empty the buffer call clear. The length property gives the current character count. isEmpty and isNotEmpty check fullness. clear is handy when you want to reuse a buffer.

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Create a StringBuffer

Question
final sb = ____();
Answer
final sb = StringBuffer();

Explanation: StringBuffer() creates an empty buffer.

2 Most efficient method to join many strings?

main.dart
final sb = StringBuffer();
for (var i = 0; i < 1000; i++) {
  sb._____(i.toString());
}
  • write Correct answer
  • concat
  • addAll
  • append

Explanation: write appends to a StringBuffer.

3 Match StringBuffer

Term Meaning
write appends one piece
writeln appends with newline
writeAll appends a list
clear empties the buffer

All lessons in Beginner