Chapters

Hide chapters

Dart Apprentice: Fundamentals

First Edition · Flutter · Dart 2.18 · VS Code 1.71

Dart Apprentice: Fundamentals

Section 1: 16 chapters
Show chapters Hide chapters

4. Strings
Written by Jonathan Sande

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

Numbers are essential in programming, but they aren’t the only type of data you need to work with in your apps. Text is also a common data type, representing things such as people’s names, their addresses, or even the complete text of a book. All of these are examples of text that an app might have to handle.

Most computer programming languages store text in a data type called a string. This chapter introduces you to strings, first by giving you background on the concept, and then by showing you how to use them in Dart.

How Computers Represent Strings

Computers think of strings as a collection of individual characters. Numbers are the language of CPUs, and all code, in every programming language, can be reduced to raw numbers. Strings are no different.

That may sound very strange. How can characters be numbers? At its base, a computer needs to be able to translate a character into the computer’s own language, and it does so by assigning each character a different number. This two-way mapping between characters and numbers is called a character set.

When you press a character key on your keyboard, you’re actually communicating the number of the character to the computer. Your computer converts that number into a picture of the character and finally, presents that picture to you.

Unicode

In isolation, a computer is free to choose whatever character set mapping it likes. If the computer wants the letter a to equal the number 10, then so be it. But when computers start talking to each other, they need to use a common character set.

c u p o 24 95 509 487

y i d é 77 66 343 270

21417 95286 23098

🎯 😂 337498 177685

🎯 😂 1V3EM 2D221 2875 9611 6W97 v u r é 82 29 56 I2

Strings and Characters in Dart

Dart, like any good programming language, can work directly with strings. It does so through the String data type. In the remainder of this chapter, you’ll learn about this data type and how to work with it.

print('Hello, Dart!');
var greeting = 'Hello, Dart!';
print(greeting);
var greeting = 'Hello, Dart!';
greeting = 'Hello, Flutter!';

Getting Characters

If you’re familiar with other programming languages, you may be wondering about a Character or char type. Dart doesn’t have that. Take a look at this example:

const letter = 'a';
var salutation = 'Hello!';
print(salutation.codeUnits);
[72, 101, 108, 108, 111, 33]
const dart = '🎯';
print(dart.codeUnits);
// [55356, 57263] 
const dart = '🎯';
print(dart.runes);
// (127919) 

Unicode Grapheme Clusters

Unfortunately, language is messy and so is Unicode. Have a look at this example:

const flag = '🇲🇳';
print(flag.runes);
// (127474, 127475)  
const family = '👨‍👩‍👧‍👦';
print(family.runes);
// (128104, 8205, 128105, 8205, 128103, 8205, 128102)         
const family = '👨‍👩‍👧‍👦';

family.length;           // 11
family.codeUnits.length; // 11
family.runes.length;     // 7         

Adding the Characters Package

This is a good opportunity to try out your first Pub package. In the root folder of your project, open pubspec.yaml.

dependencies:
  characters: ^1.2.1

dart pub get
import 'package:characters/characters.dart';
const family = '👨‍👩‍👧‍👦';
family.characters.length; // 1         

Single Quotes vs. Double Quotes

Dart allows you to use either single quotes or double quotes for string literals. Both of these are fine:

'I like cats'
"I like cats"
"my cat's food"
'my cat\'s food'

Concatenation

You can do much more than create simple strings. Sometimes you need to manipulate a string, and one common way to do so is to combine it with another string. This is called concatenation…with no relation to the aforementioned felines.

var message = 'Hello' + ' my name is ';
const name = 'Ray';
message += name;
// 'Hello my name is Ray'

Interpolation

You can also build up a string by using interpolation, which is a special Dart syntax that lets you build a string in a manner that’s easy for other people reading your code to understand:

const name = 'Ray';
const introduction = 'Hello my name is $name';
// 'Hello my name is Ray'
const oneThird = 1 / 3;
const sentence = 'One third is $oneThird.';
One third is 0.3333333333333333.
final sentence = 'One third is ${oneThird.toStringAsFixed(3)}.';
One third is 0.333.

Exercises

  1. Create a string constant called firstName and initialize it to your first name. Also create a string constant called lastName and initialize it to your last name.
  2. Create a string constant called fullName by adding the firstName and lastName constants together, separated by a space.
  3. Using interpolation, create a string constant called myDetails that uses the fullName constant to create a string introducing yourself. For example, Ray Wenderlich’s string would read: Hello, my name is Ray Wenderlich.

Multi-Line Strings

Dart has a neat way to express strings that contain multiple lines, which can be rather useful when you need to use very long strings in your code.

const bigString = '''
You can have a string
that contains multiple
lines
by
doing this.''';
print(bigString);
You can have a string
that contains multiple
lines
by
doing this.
const oneLine = 'This is only '
    'a single '
    'line '
    'at runtime.';
const oneLine = 'This is only ' +
    'a single ' +
    'line ' +
    'at runtime.';
This is only a single line at runtime.
const twoLines = 'This is\ntwo lines.';
This is
two lines.
const rawString = r'My name \n is $name.';
My name \n is $name.

Inserting Characters From Their Codes

Similar to the way you can insert a newline character into a string using the \n escape sequence, you can also add Unicode characters if you know their codes. Take the following example:

print('I \u2764 Dart\u0021');

print('I love \u{1F3AF}');

Challenges

Before moving on, here are some challenges to test your knowledge of strings. It’s best if you try to solve them yourself, but solutions are available with the supplementary materials for this book if you get stuck.

Challenge 1: Same Same, but Different

This string has two flags that look the same. But they aren’t! One of them is the flag of Chad and the other is the flag of Romania.

const twoCountries = '🇹🇩🇷🇴';      

Challenge 2: How Many?

Given the following string:

const vote = 'Thumbs up! 👍🏿';  

Challenge 3: Find the Error

What is wrong with the following code?

const name = 'Ray';
name += ' Wenderlich';

Challenge 4: In Summary

What is the value of the constant named summary?

const number = 10;
const multiplier = 5;
final summary = '$number \u00D7 $multiplier = ${number * multiplier}';

Key Points

  • Unicode is the standard representation for mapping characters to numbers.
  • Dart uses UTF-16 values known as code units to encode Unicode strings.
  • A single mapping in Unicode is called a code point, which is known as a rune in Dart.
  • User-perceived characters may be composed of one or more code points and are called grapheme clusters.
  • You can combine strings by using the addition operator.
  • You can make multi-line strings using three single quotes or double quotes.
  • You can use string interpolation to build a string in place.
Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.
© 2024 Kodeco Inc.

You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now