๐ŸŽ“ A1Learner
๐Ÿ”
0 of 40 lessons completed

Dart Strings

A string is a value that holds text. Dart writes a string inside single quotes and gives it the type String.

Joining two strings

The + sign joins the second string to the end of the first. The joined text prints as one line.

void main() {
  var greeting = 'Hello, ' + 'Dart';
  print(greeting);
}

Counting characters

length counts every character in a string. The counts 4 and 5 match the letters in each word.

void main() {
  print('dart'.length);
  print('hello'.length);
}

One character by index

The index counts from 0, so index 1 is the second character. The prints show d first and a second.

void main() {
  print('dart'[0]);
  print('dart'[1]);
}

An empty string

Two single quotes with nothing between them make an empty string. Its length is 0.

void main() {
  print(''.length);
}

Example

void main() {
  var name = 'Sam' + ' ' + 'Lee';
  print(name);
  print(name.length);
}

Key points

  • Use + to join two strings into one string.
  • length gives the number of characters in a string.
  • An index is the position of a character in a string.
  • The first character sits at index 0.
  • Use square brackets after a string to read the character at an index.
  • A character read from a string is a String with length 1.

In this example, three strings join into the name Sam Lee. The length of the joined string is 7, and that count includes the space.

Note

In Go, reading a string by index gives a byte number, and Dart gives a one-character String instead.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท DartPad

Exercise

What does 'dart'[1] print?