Watch the video (12 min)
On this page27 sections
  1. Prerequisites
  2. Connection With Previous Lectures
  3. Learning Objectives
  4. 1. What Is a String?
  5. 2. Single or Double Quotes
  6. 3. Quotes Inside a String
  7. 4. Escape Sequences
  8. 5. Interpolation with $
  9. 6. Expressions with ${}
  10. 7. Joining Strings with +
  11. 8. Multi-line Strings
  12. 9. Raw Strings
  13. 10. Length and Indexes
  14. 11. Changing Case and Trimming
  15. 12. Searching Inside a String
  16. 13. Cutting and Replacing
  17. 14. Strings Never Change
  18. 15. A Real-World Example
  19. Code Examples
  20. Common Beginner Mistakes
  21. Best Practices
  22. Mini Challenge
  23. Practice Questions
  24. Practice Answers
  25. Quick Revision
  26. Key Takeaways
  27. What's Next?

Lecture 08 — Strings

Category2 — Variables & Data Types
Lecture008 of 140
Estimated video length12 min
TargetDart 3.12.2
LevelBeginner

So far a string was just text between quotes. Now you will learn to build, shape, and question text: put quotes inside it, split it over lines, measure it, and change its case.

Contents

Prerequisites · Connection · Objectives · Lesson · Code Examples · Common Mistakes · Best Practices · Mini Challenge · Practice Questions · Answers · Takeaways

Every error message in this lecture is real. Each one was produced by running the code shown on Dart 3.12.2, so you will recognize it when you meet it yourself.


Prerequisites

Students should already understand, from Lectures 001–007:

  • main(), print(), and comments
  • declaring variables with a type or with var
  • final and const
  • the basic types String, int, double, and bool
  • simple string interpolation such as 'Name: $name'

Connection With Previous Lectures

Since Lecture 004 we have printed text like this:

dart
var name = 'Ali';
print('Name: $name');

That covers simple messages. But try to print Ali's marks and the apostrophe breaks the program. Try to print an address over three lines, count the letters in a password, or show a name in capital letters — we have no way to do any of it yet. Lecture 007 told us String is Dart's type for text. This lecture shows what a String can actually do.


Learning Objectives

By the end of this lecture you will be able to:

  • Create strings with single and double quotes
  • Put quotes, new lines, and tabs inside a string using escape sequences
  • Insert variables and calculations into a string with $ and ${}
  • Join strings together with +
  • Write multi-line and raw strings
  • Measure a string with length and read single characters by index
  • Use common string methods: change case, trim, search, cut, and replace
  • Explain why string methods return a new string instead of changing the old one

1. What Is a String?

A string is a piece of text: a sequence of characters such as letters, digits, spaces, and symbols. In Dart its type is String.

Analogy — think of beads on a thread. Each bead is one character, and the thread keeps them in order. 'Ali' is three beads: A, l, i.

dart
void main() {
  String city = 'Lahore';
  var greeting = 'Hello, world!';
  print(city);
  print(greeting);
}
output
Lahore
Hello, world!

Digits inside quotes are text too: '2025' is a String, not an int.


2. Single or Double Quotes

Dart accepts both 'single' and "double" quotes. They produce exactly the same string:

dart
void main() {
  var first = 'Sara';
  var second = "Sara";
  print(first);
  print(second);
}
output
Sara
Sara

Dart's style guide prefers single quotes, so this course uses them unless there is a reason not to.


3. Quotes Inside a String

A string ends at the next matching quote. An apostrophe inside single quotes ends the string too early. The simplest fix is to wrap the text in the other kind of quote:

dart
void main() {
  print("Ali's marks");
  print('She said "hello"');
}
output
Ali's marks
She said "hello"

4. Escape Sequences

Sometimes you cannot switch quotes, or you need a character you cannot type, like a line break. A backslash \ tells Dart "the next character is special":

WriteMeans
\'a single quote
\"a double quote
\na new line
\ta tab
\\one backslash
\$a dollar sign
dart
void main() {
  print('Ali\'s marks');
  print('Line one\nLine two');
  print('Name:\tSara');
  print('Folder: C:\\Users');
}
output
Ali's marks
Line one
Line two
Name:	Sara
Folder: C:\Users

5. Interpolation with $

You already know that $ followed by a variable name inserts its value. This is called string interpolation, and it works with any type:

dart
void main() {
  var name = 'Zayan';
  var age = 6;
  var height = 3.9;
  var isStudent = true;
  print('$name is $age, $height ft tall, student: $isStudent');
}
output
Zayan is 6, 3.9 ft tall, student: true

Dart turns each value into text for you — no conversion needed.


6. Expressions with ${}

$name only works for a plain variable name. For anything more — a calculation, or a property like length — wrap it in curly braces ${...}:

dart
void main() {
  var price = 250;
  var quantity = 4;
  print('Total: ${price * quantity}');
  print('Next year Ali will be ${20 + 1}');
}
output
Total: 1000
Next year Ali will be 21

To print a real dollar sign, escape it: 'Cost: \$5' prints Cost: $5.


7. Joining Strings with +

The + operator joins two strings into one. This is called concatenation:

dart
void main() {
  var firstName = 'Sara';
  var lastName = 'Khan';
  var fullName = firstName + ' ' + lastName;
  print(fullName);
}
output
Sara Khan

+ only joins a String to another String. For numbers, use interpolation instead: 'Age: $age'. Dart's style guide prefers interpolation for building messages anyway — it is shorter and easier to read.

Two string literals written side by side are joined automatically, which is handy for long text:

dart
void main() {
  var message =
      'Welcome to the Dart course. '
      'Today we study strings.';
  print(message);
}
output
Welcome to the Dart course. Today we study strings.

8. Multi-line Strings

Three quotes in a row — ''' or """ — start a string that can span several lines. The line breaks you type become part of the text:

dart
void main() {
  var address = '''
Ali Raza
House 12, Street 5
Lahore''';
  print(address);
}
output
Ali Raza
House 12, Street 5
Lahore

A line break straight after the opening ''' is ignored, so the text starts cleanly. Interpolation works here too.


9. Raw Strings

Put an r before the opening quote and Dart treats every character literally: no escape sequences, no interpolation. This is useful for text full of backslashes, such as Windows file paths:

dart
void main() {
  var normal = 'Tab:\tdone';
  var raw = r'Tab:\tdone';
  print(normal);
  print(raw);
  print(r'Price: $price');
}
output
Tab:	done
Tab:\tdone
Price: $price

10. Length and Indexes

Every string knows how many characters it has. Read it with .length:

dart
void main() {
  var name = 'Ali';
  var password = 'dart2025';
  print(name.length);
  print(password.length);
  print(''.length);
}
output
3
8
0

'' is the empty string — a string with no characters. Spaces count as characters.

Each character has a position called an index, and counting starts at 0. Use square brackets to read one character:

dart
void main() {
  var name = 'Sara';
  print(name[0]);
  print(name[3]);
  print(name[name.length - 1]);
}
output
S
a
a

The last index is always length - 1. Indexes come back in a big way when we study lists in Lecture 040.


11. Changing Case and Trimming

A method is an action a value can perform. You call it with a dot and parentheses. These methods return a tidied-up copy of the string:

dart
void main() {
  var name = 'Sara Khan';
  print(name.toUpperCase());
  print(name.toLowerCase());

  var input = '   ali@mail.com   ';
  print('[${input.trim()}]');
  print('[${input.trimLeft()}]');
  print('[${input.trimRight()}]');
}
output
SARA KHAN
sara khan
[ali@mail.com]
[ali@mail.com   ]
[   ali@mail.com]

trim() removes spaces from both ends — perfect for text a user typed. The square brackets in the output just make the spaces visible.


12. Searching Inside a String

These methods answer questions about the text. The first three give a bool; indexOf gives a position:

dart
void main() {
  var email = 'sara@school.com';
  print(email.contains('@'));
  print(email.startsWith('sara'));
  print(email.endsWith('.org'));
  print(email.indexOf('@'));
  print(email.indexOf('#'));
  print(email.isEmpty);
  print(email.isNotEmpty);
}
output
true
true
false
4
-1
false
true

indexOf returns -1 when the text is not found. Searches are case-sensitive: 'Sara'.contains('sara') is false. We will use these bool results to make decisions once we reach if statements in Lecture 022.


13. Cutting and Replacing

substring(start, end) copies the characters from index start up to — but not including — index end. Leave out end to go to the last character:

dart
void main() {
  var word = 'Programming';
  print(word.substring(0, 7));
  print(word.substring(3));
}
output
Program
gramming

replaceAll(from, to) swaps every match; padLeft(width, char) fills a string out to a fixed width:

dart
void main() {
  var sentence = 'I like tea. Tea is great.';
  print(sentence.replaceAll('tea', 'coffee'));
  print('7'.padLeft(3, '0'));
  print('-' * 10);
}
output
I like coffee. Tea is great.
007
----------

Only the lowercase tea changed — replacing is case-sensitive too. The last line shows that * repeats a string a given number of times.


14. Strings Never Change

A string can never be modified once created — it is immutable. Every method above returns a new string and leaves the original alone:

dart
void main() {
  var name = 'ali';
  name.toUpperCase();
  print(name);
  name = name.toUpperCase();
  print(name);
}
output
ali
ALI

The first call made 'ALI' and threw it away. To keep the result, assign it — to the same variable or a new one.


15. A Real-World Example

A sign-up form receives a messy name and email. Clean them up and print a receipt:

dart
void main() {
  var rawName = '  sara khan ';
  var rawEmail = ' Sara@School.COM';
  var fee = 1500;

  var name = rawName.trim().toUpperCase();
  var email = rawEmail.trim().toLowerCase();
  var initial = name[0];

  print('''
Registration
------------
Name:    $name
Initial: $initial
Email:   $email
Valid:   ${email.contains('@')}
Letters: ${name.length}
Fee:     Rs. $fee''');
}
output
Registration
------------
Name:    SARA KHAN
Initial: S
Email:   sara@school.com
Valid:   true
Letters: 9
Fee:     Rs. 1500

Method calls can be chained: rawName.trim().toUpperCase() trims first, then converts the trimmed copy. The multi-line string lays out the receipt exactly as it appears.


Code Examples

Example 1 — Single and Double Quotes

dart
void main() {
  var city = 'Karachi';
  var country = "Pakistan";
  print(city);
  print(country);
}
output
Karachi
Pakistan

Example 2 — Escape Sequences

dart
void main() {
  print('Sara\'s book');
  print('Name\tMarks');
  print('Ali\t85');
  print('First\nSecond');
}
output
Sara's book
Name	Marks
Ali	85
First
Second

Example 3 — Interpolation and Expressions

dart
void main() {
  var name = 'Zayan';
  var apples = 3;
  var oranges = 2;
  print('$name has ${apples + oranges} fruits.');
}
output
Zayan has 5 fruits.

Example 4 — Concatenation

dart
void main() {
  var firstName = 'Ali';
  var lastName = 'Raza';
  var fullName = firstName + ' ' + lastName;
  print(fullName);
  print('Hello, ' + fullName + '!');
}
output
Ali Raza
Hello, Ali Raza!

Example 5 — Multi-line and Raw Strings

dart
void main() {
  var poem = '''
Roses are red,
Dart is blue.''';
  var path = r'C:\new\temp';
  print(poem);
  print(path);
}
output
Roses are red,
Dart is blue.
C:\new\temp

How it works

  1. The ''' string keeps its line break, so the poem prints on two lines.
  2. Without the r, \n in the path would become a line break and \t a tab.
  3. The raw string prints every backslash exactly as written.

Example 6 — Length, Index, and Case

dart
void main() {
  var word = 'flutter';
  print(word.length);
  print(word[0]);
  print(word.toUpperCase());
  print(word.substring(0, 4));
}
output
7
f
FLUTTER
flut

Example 7 — Student Marks Card

dart
void main() {
  var student = 'sara';
  var math = 90;
  var science = 84;
  print('Student: ${student.toUpperCase()}');
  print('Math:\t$math');
  print('Science:\t$science');
  print('Total:\t${math + science}');
}
output
Student: SARA
Math:	90
Science:	84
Total:	174

How it works

  1. ${student.toUpperCase()} calls a method inside the string, so it needs braces.
  2. \t puts a tab between each label and its mark.
  3. ${math + science} calculates the total right inside the message.

Example 8 — Shopping Receipt

dart
void main() {
  var item = 'Notebook';
  var price = 120;
  var quantity = 5;
  var line = '=' * 20;
  print(line);
  print('Item: $item');
  print('Qty:  $quantity x Rs. $price');
  print('Total: Rs. ${price * quantity}');
  print(line);
}
output
====================
Item: Notebook
Qty:  5 x Rs. 120
Total: Rs. 600
====================

How it works

  1. '=' * 20 builds a divider of twenty = characters.
  2. $quantity and $price are plain variables, so no braces are needed.
  3. ${price * quantity} is a calculation, so it needs braces.

Example 9 — Bank Account Mask

dart
void main() {
  var owner = 'Ali';
  var account = '4021889917';
  var balance = 25000.5;
  var lastFour = account.substring(account.length - 4);
  print('Owner: $owner');
  print('Account: ******$lastFour');
  print('Balance: Rs. $balance');
}
output
Owner: Ali
Account: ******9917
Balance: Rs. 25000.5

How it works

  1. account.length is 10, so account.length - 4 is 6.
  2. substring(6) copies from index 6 to the end: '9917'.
  3. Banks show only the last four digits; the rest are hidden behind *.

Example 10 — Temperature Report

dart
void main() {
  var city = 'islamabad';
  var celsius = 30.0;
  var fahrenheit = celsius * 9 / 5 + 32;
  print('''
City:       ${city.toUpperCase()}
Celsius:    $celsius
Fahrenheit: $fahrenheit''');
}
output
City:       ISLAMABAD
Celsius:    30.0
Fahrenheit: 86.0

How it works

  1. fahrenheit is calculated first: 30.0 * 9 / 5 + 32 is 86.0.
  2. The multi-line string lines up the labels exactly as typed.
  3. Interpolation works inside ''' strings just like in normal ones.

Common Beginner Mistakes

1. An apostrophe inside single quotes

dart
void main() {
  // print('It's sunny'); // ✗
}
output
Error: String starting with ' must end with '.
  print('It's sunny');
                   ^^^

Dart thinks the string ends at It. Use "It's sunny" or 'It\'s sunny'.

2. Adding a number to a string with +

dart
void main() {
  var age = 20;
  // print('Age: ' + age); // ✗
}
output
Error: A value of type 'int' can't be assigned to a variable of type 'String'.
  print('Age: ' + age);
                  ^

+ joins strings only. Write 'Age: $age'.

3. Forgetting braces for a property

dart
void main() {
  var name = 'Ali';
  print('Letters: $name.length');
  print('Letters: ${name.length}');
}
output
Letters: Ali.length
Letters: 3

No error — just wrong output. $name stops at the dot, and .length is printed as plain text. Anything beyond a bare name needs ${}.

4. A dollar sign that is not a variable

dart
void main() {
  // print('Cost: $5'); // ✗
  print('Cost: \$5');
}
output
Error: A '$' has special meaning inside a string, and must be followed by an identifier or an expression in curly braces ({}).
Try adding a backslash (\) to escape the '$'.

The second line shows the fix: escape it as \$, or use a raw string.

5. Calling a method and ignoring the result

dart
void main() {
  var name = 'ali';
  name.toUpperCase(); // ✗ result thrown away
  print(name);
}
output
ali

Strings are immutable. Write name = name.toUpperCase();.

6. Going past the end of a string

dart
void main() {
  var name = 'Ali';
  // print(name.substring(0, 5)); // ✗ only 3 characters
}
output
Unhandled exception:
RangeError (end): Invalid value: Not in inclusive range 0..3: 5

This one compiles and then crashes while running. name has only 3 characters, so end can be at most 3.

7. Trying to change one character

dart
void main() {
  var name = 'Ali';
  // name[0] = 'B'; // ✗
}
output
Error: The operator '[]=' isn't defined for the type 'String'.

You can read name[0] but never write to it. Build a new string instead.


Best Practices

  • Prefer single quotes; switch to double quotes when the text contains an apostrophe.
  • Use interpolation ('Hi $name') instead of + to build messages.
  • Use $name for a plain variable and ${...} for anything else.
  • Use ''' for text that really spans lines, and r'...' for text full of backslashes.
  • trim() text that comes from a user before you check or store it.
  • Remember that indexes start at 0 and the last one is length - 1.
  • Always store the result of a string method — the original never changes.

Mini Challenge

Sara types her username as ' SaraK_2025 '. Clean it up and print a summary: the trimmed name in lowercase, its length, its first letter, and whether it contains '_'.

Your program should print exactly:

output
Username: sarak_2025
Length: 10
First letter: s
Has underscore: true

Try it yourself before opening the solution.

Show solution
dart
void main() {
  var input = '  SaraK_2025  ';
  var username = input.trim().toLowerCase();
  print('Username: $username');
  print('Length: ${username.length}');
  print('First letter: ${username[0]}');
  print('Has underscore: ${username.contains('_')}');
}
output
Username: sarak_2025
Length: 10
First letter: s
Has underscore: true

How it works

  1. trim() removes the four spaces, then toLowerCase() lowers every letter.
  2. The trimmed name has 10 characters; the spaces are no longer counted.
  3. username[0] is the first character, and contains('_') returns a bool.

Practice Questions

Work through these in order — they run from beginner to application to challenge. Every question gives you exact values, so you can compare your output with the answers.

Beginner

  1. Store 'Dart' in a variable and print it, then print its length.
  2. Print Zayan's toy twice: once using double quotes, once using an escape sequence.
  3. Print Monday, Tuesday, and Wednesday on three lines using a single print() and \n.

Application

  1. Store name = 'Ali' and marks = 88, then print Ali scored 88 marks. using interpolation.
  2. Store width = 6 and height = 7, then print Area: 42 by calculating the area inside the string.
  3. Store city = 'peshawar' and print it in capital letters, then print its first and last characters.
  4. Store ' hello dart ', trim it, and print it inside square brackets: [hello dart].
  5. Store word = 'Fantastic' and print Fan and tastic using substring.

Challenge

  1. Store the sentence 'I love cats. cats are cute.'. Print it with every cats replaced by dogs, then print the position of the first . in the original sentence.
  2. Store a phone number '03001234567'. Print Phone: 0300-*****67 by combining substring and * — no typing the digits by hand.

Practice Answers

Question 1 — Solution

dart
void main() {
  var language = 'Dart';
  print(language);
  print(language.length);
}
output
Dart
4

Question 2 — Solution

dart
void main() {
  print("Zayan's toy");
  print('Zayan\'s toy');
}
output
Zayan's toy
Zayan's toy

Question 3 — Solution

dart
void main() {
  print('Monday\nTuesday\nWednesday');
}
output
Monday
Tuesday
Wednesday

Question 4 — Solution

dart
void main() {
  var name = 'Ali';
  var marks = 88;
  print('$name scored $marks marks.');
}
output
Ali scored 88 marks.

Question 5 — Solution

dart
void main() {
  var width = 6;
  var height = 7;
  print('Area: ${width * height}');
}
output
Area: 42

Question 6 — Solution

dart
void main() {
  var city = 'peshawar';
  print(city.toUpperCase());
  print(city[0]);
  print(city[city.length - 1]);
}
output
PESHAWAR
p
r

Question 7 — Solution

dart
void main() {
  var text = '   hello dart   ';
  print('[${text.trim()}]');
}
output
[hello dart]

Question 8 — Solution

dart
void main() {
  var word = 'Fantastic';
  print(word.substring(0, 3));
  print(word.substring(3));
}
output
Fan
tastic

substring(0, 3) stops just before index 3, and substring(3) starts there.

Question 9 — Solution

dart
void main() {
  var sentence = 'I love cats. cats are cute.';
  print(sentence.replaceAll('cats', 'dogs'));
  print(sentence.indexOf('.'));
}
output
I love dogs. dogs are cute.
11

indexOf finds only the first match, at index 11.

Question 10 — Solution

dart
void main() {
  var phone = '03001234567';
  var start = phone.substring(0, 4);
  var end = phone.substring(phone.length - 2);
  print('Phone: $start-${'*' * 5}$end');
}
output
Phone: 0300-*****67

start is the first four digits and end the last two. '*' * 5 builds the mask, and it needs braces because it is an expression.


Quick Revision

  1. What is the difference between 'Sara' and "Sara"?
  2. Name two ways to put an apostrophe inside a string.
  3. What do \n and \t produce?
  4. When do you need ${} instead of just $?
  5. Why does 'Age: ' + 20 fail?
  6. What does an r before a string change?
  7. What is the index of the first character? Of the last?
  8. Why does name.toUpperCase(); on its own not change name?

Key Takeaways

  • A String is a sequence of characters, written in single or double quotes.
  • A backslash starts an escape sequence: \', \", \n, \t, \\, \$.
  • $name inserts a variable; ${...} inserts any expression.
  • + joins strings only — interpolation is the preferred way to build messages.
  • ''' creates multi-line strings; r'...' creates raw strings with no escapes.
  • length counts characters, and indexes run from 0 to length - 1.
  • Methods such as toUpperCase, trim, contains, indexOf, substring, and replaceAll shape and search text.
  • Strings are immutable: every method returns a new string, so store the result.

What's Next?

Lecture 09 — Numbers. Strings handle text; most programs also need to count, measure, and calculate. Next we take a closer look at Dart's number types, int and double: how they differ, how they print, and the useful properties and methods they offer — just as String does.


Video lecture

Subscribe
Placeholder video — the real recording isn't linked yet.