CodeBlanks Logo Icon CodeBlanks

split and join

Learn string splitting with split and join.

split and join

In Dart you split a string with split. You pass a delimiter; the string is divided on it and a List<String> is returned. For example "a,b,c".split(",") gives you ["a", "b", "c"].

To do the reverse, that is to combine a list into a single string, use join. ["a", "b"].join("-") returns "a-b". Together they are very handy for parsing CSV lines, log entries or user input.

Choosing a delimiter

The delimiter does not have to be a single character. A multi-character delimiter works too: "a::b::c".split("::") is valid. Likewise join accepts a long separator; ["a", "b"].join(" - ") places - between each element.

An empty delimiter "".split("") breaks the string into individual characters. This is a convenient way to walk a string as a list of characters. If the list is empty, join still returns an empty string, so an empty check is usually not needed.

Practice Your turn: split and join

Split the string "apple,pear,banana" on the comma and join it back with " - ". Print the result with print.

Starter code

main.dart
void main() {
  // Split "apple,pear,banana" on the comma
  // Join with " - " and print
}

Sample solution

main.dart
void main() {
  final fruit = "apple,pear,banana";
  final parts = fruit.split(",");
  print(parts.join(" - "));
}

Expected output

apple - pear - banana

Questions and answers

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

1 Which method divides a string into parts?

main.dart
final part = "a,b,c"._____(",");
  • split Correct answer
  • join
  • trim
  • replaceAll

Explanation: split divides the string on the given delimiter.

2 The split call

Question
final parts = "apple,pear,banana".____(",");
Answer
final parts = "apple,pear,banana".split(",");

Explanation: split(",") breaks the string on commas.

3 Match split and join

Term Meaning
split divides a string
join combines a list
"," (delimiter) splits on commas
List<String> split's return type

All lessons in Beginner