Skip to content
Tutorials Center
My learning

Topics

Lesson 6 of 61 ยท Types and Operators

Strings and String Interpolation

Master Dart strings: single and double quotes, raw and multiline strings, interpolation, common methods, StringBuffer for building text, and how runes handle Unicode.

Text is everywhere in programs: names, messages, file paths, JSON. In Dart a piece of text is a String, an immutable sequence of UTF-16 code units with a long list of useful methods. You have already used strings and interpolation in the first lessons; this one fills in the details: the different literal forms, the methods you will reach for daily, how to build large strings efficiently, and what happens with characters outside the basic alphabet.

The Dart code is read-only. TypeScript stand-ins let you run the matching ideas, and the lesson points out where JavaScript strings differ.

Writing string literals

Single and double quotes are equivalent. Choose one style for a project (the Dart style guide prefers single quotes) and switch only to avoid escaping:

DART
void main() {
  var a = 'It\'s fine';     // escaped quote
  var b = "It's fine";      // double quotes avoid the escape
  var c = 'She said "hi"';  // and the other way around
  print(a == b);            // true
  print(c);
}

Neighbouring literals are joined automatically, even across lines. This is handy for long text, since it needs no +:

DART
void main() {
  var message = 'Dart is a client-optimized language '
      'for fast apps on any platform.';
  print(message);
}

You can still use + to join strings, and * to repeat one:

DART
void main() {
  print('Hello, ' + 'world');   // Hello, world
  print('ab' * 3);              // ababab
  print('-' * 20);              // a divider line
}

Escapes, raw strings and multiline strings

Inside a normal string, a backslash starts an escape: \n is a newline, \t a tab, \\ a backslash and \$ a dollar sign. A raw string starts with r and turns escapes and interpolation off, which is ideal for regular expressions and Windows paths:

DART
void main() {
  print('Line one\nLine two');
  print(r'C:\Users\ada\notes.txt');   // the \n stays as two characters
  print(r'Price in $: 5');            // no interpolation
}

Three quotes in a row make a multiline string, which keeps line breaks exactly as you type them:

DART
void main() {
  var poem = '''
Roses are red,
Violets are blue,
Dart has types,
And so do you.''';
  print(poem);
}

A newline directly after the opening ''' is ignored, so the text starts on the next line.

TypeScript Raw and multiline text (TypeScript stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Interpolation, again

You know $name and ${expression}. A few more details:

DART
void main() {
  var items = ['pen', 'ink'];
  var price = 2.5;
  print('You bought ${items.length} items: $items');
  print('Total: \$${(items.length * price).toStringAsFixed(2)}');
  print('Shout: ${items.first.toUpperCase()}!');
}
TEXT
You bought 2 items: [pen, ink]
Total: $5.00
Shout: PEN!

Anything you interpolate is converted with its toString() method. A null becomes the text null, which is a common source of strings like "Hello null" if you forget to check. Interpolation can nest: you can use a string with its own ${...} inside the braces.

The members you will use most

Strings are objects, and the most useful members fall into a few groups.

Inspecting:

DART
void main() {
  var s = 'Hello, Dart';
  print(s.length);              // 11
  print(s.isEmpty);             // false
  print(s.isNotEmpty);          // true
  print(s[0]);                  // H  (a String of length 1, not a char type)
  print(s.contains('Dart'));    // true
  print(s.startsWith('Hell'));  // true
  print(s.endsWith('t'));       // true
  print(s.indexOf('l'));        // 2
  print(s.indexOf('z'));        // -1 (not found)
}

Slicing and changing. Remember that strings are immutable: every method returns a new string and leaves the original alone.

DART
void main() {
  var s = '  Hello, Dart  ';
  print(s.trim());                       // Hello, Dart
  print(s.trim().toUpperCase());         // HELLO, DART
  print(s.trim().substring(7));          // Dart
  print(s.trim().substring(0, 5));       // Hello
  print(s.replaceAll('l', 'L'));         //   HeLLo, Dart
  print('7'.padLeft(3, '0'));            // 007
  print('ab'.padRight(5, '.'));          // ab...
}

substring(start, end) takes the end index as exclusive. Going outside the string throws a RangeError.

Splitting and joining:

DART
void main() {
  var csv = 'red,green,blue';
  var parts = csv.split(',');          // [red, green, blue]
  print(parts.length);                 // 3
  print(parts.join(' | '));            // red | green | blue
}

Comparing. Use == to compare contents, compareTo for ordering:

DART
void main() {
  print('apple' == 'apple');            // true (value comparison)
  print('apple'.compareTo('banana'));   // -1
  // print('a' < 'b');                  // error: String has no < operator
}

Dart strings have no < operator, so sort with compareTo. Also note == is case-sensitive; compare lowercase copies for a case-insensitive check.

TypeScript Common string work (TypeScript stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Building strings with StringBuffer

Because strings are immutable, adding text to one in a loop creates a new string every time. For a handful of joins that is fine. For thousands, use a StringBuffer, which collects pieces and builds the result once:

DART
void main() {
  var buffer = StringBuffer();
  for (var i = 1; i <= 3; i++) {
    buffer.write('Row $i');
    buffer.writeln();             // adds a newline
  }
  buffer.writeAll(['a', 'b', 'c'], '-');
  print(buffer.toString());
}
TEXT
Row 1
Row 2
Row 3
a-b-c

The methods are write, writeln, writeAll, writeCharCode and clear. Call toString() once at the end.

flowchart LR
    A["write('Row 1')"] --> B["StringBuffer<br/>(collects pieces)"]
    C["write('Row 2')"] --> B
    D["writeAll(...)"] --> B
    B -->|"toString()"| E["one final String"]

A StringBuffer gathers pieces cheaply and creates the String only once.

Unicode: code units, runes and characters

A Dart String is a sequence of UTF-16 code units. Letters in the basic range take one unit, but many symbols, such as emoji, take two (a surrogate pair). That changes what length counts:

DART
void main() {
  var smile = '๐Ÿ˜€';
  print(smile.length);            // 2  (two UTF-16 code units)
  print(smile.runes.length);      // 1  (one Unicode code point)
  print(smile.codeUnits);         // [55357, 56832]
  print(smile.runes.first.toRadixString(16));  // 1f600
  print(String.fromCharCode(0x41));            // A
}

runes yields full code points, so it counts what most people call a character, with one exception: some visible characters are built from several code points (a family emoji, or a letter plus an accent mark). For text that a user would count as single "characters", use the characters package from pub.dev, whose str.characters.length counts grapheme clusters. For ordinary English text and most text processing, length and indexing are fine, but never slice a string in the middle of a surrogate pair.

TypeScript Code units versus code points (TypeScript stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does r'C: ew' contain?

    A string with the r prefix is raw. Backslashes and dollar signs have no special meaning, so no escape is processed.
  2. 2. With var s = 'dart';, what does s.toUpperCase(); do to s?

    Strings are immutable. toUpperCase returns a new string; you must use the result, for example s = s.toUpperCase().
  3. 3. Which tool is best for appending many small pieces of text in a loop?

    StringBuffer collects the pieces and builds the final string once, avoiding a new string for every append.
  4. 4. Why does '๐Ÿ˜€'.length return 2 in Dart?

    Dart strings are sequences of UTF-16 code units. Characters outside the basic range use a surrogate pair, so length is 2 while runes.length is 1.

Summary

  • Single and double quotes are equivalent; neighbouring literals join automatically; r'...' is raw and '''...''' is multiline.
  • Interpolate with $name or ${expression}; any object is converted with toString().
  • Strings are immutable, so methods like trim, substring, replaceAll and toUpperCase return new strings.
  • split/join, contains, startsWith, indexOf, padLeft and compareTo cover most everyday work.
  • Use StringBuffer to build long text; use runes or the characters package when Unicode matters.

Next, combine values with Booleans and Operators.