CodeBlanks Logo Icon CodeBlanks

Summary - Advanced strings

Combine split, RegExp and StringBuffer to write a CSV parser.

Summary - Advanced strings

In this group you saw four powerful string tools: split and join for string-list conversion, replaceAll for bulk replacement, trim and padLeft for formatting, RegExp for pattern search, StringBuffer for efficient building. Now we combine them all in a CSV parser.

A CSV line holds comma-separated fields. You split with split, clean spaces with trim, validate digits with RegExp and produce a new formatted output with StringBuffer. This is string tools working together on a real task.

Practice Your turn: parse a CSV line

Split the line "anna, 28 , paris" on the comma, clean each part with trim and join them with StringBuffer using "|" as the separator. Print the result.

Starter code

main.dart
void main() {
  // Split "anna, 28 , paris" on the comma
  // Trim each part
  // Join with StringBuffer and "|" then print
}

Sample solution

main.dart
void main() {
  final line = "anna, 28 , paris";
  final parts = line.split(",").map((s) => s.trim()).toList();
  final sb = StringBuffer();
  for (var i = 0; i < parts.length; i++) {
    if (i > 0) sb.write("|");
    sb.write(parts[i]);
  }
  print(sb.toString());
}

Expected output

anna|28|paris

Practice Your turn: validate and format fields

Split "book, 120 , 2024", trim each part. Check the third part with RegExp(r"\d{4}") using hasMatch and print the result.

Starter code

main.dart
void main() {
  // Split "book, 120 , 2024" and trim each part
  // Check the third part with a four-digit pattern
  // Print the result
}

Sample solution

main.dart
void main() {
  final line = "book, 120 , 2024";
  final parts = line.split(",").map((s) => s.trim()).toList();
  print(RegExp(r"\d{4}").hasMatch(parts[2]));
}

Expected output

true

Questions and answers

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

1 First step to extract fields from a CSV line?

main.dart
final line = "anna,28,paris";
final fields = line._____(",");
  • trim
  • split Correct answer
  • join
  • pad

Explanation: split turns the fields into a list.

2 Match the CSV tools

Term Meaning
split(",") splits the fields
trim() cuts spaces
RegExp(r"\d+") validates the age
StringBuffer builds the output

All lessons in Beginner