On this page27 sections
- Prerequisites
- Connection With Previous Lectures
- Learning Objectives
- 1. What Is a String?
- 2. Single or Double Quotes
- 3. Quotes Inside a String
- 4. Escape Sequences
- 5. Interpolation with $
- 6. Expressions with ${}
- 7. Joining Strings with +
- 8. Multi-line Strings
- 9. Raw Strings
- 10. Length and Indexes
- 11. Changing Case and Trimming
- 12. Searching Inside a String
- 13. Cutting and Replacing
- 14. Strings Never Change
- 15. A Real-World Example
- Code Examples
- Common Beginner Mistakes
- Best Practices
- Mini Challenge
- Practice Questions
- Practice Answers
- Quick Revision
- Key Takeaways
- What's Next?
Lecture 08 — Strings
| Category | 2 — Variables & Data Types |
| Lecture | 008 of 140 |
| Estimated video length | 12 min |
| Target | Dart 3.12.2 |
| Level | Beginner |
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 finalandconst- the basic types
String,int,double, andbool - simple string interpolation such as
'Name: $name'
Connection With Previous Lectures
Since Lecture 004 we have printed text like this:
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
lengthand 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.
void main() {
String city = 'Lahore';
var greeting = 'Hello, world!';
print(city);
print(greeting);
}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:
void main() {
var first = 'Sara';
var second = "Sara";
print(first);
print(second);
}Sara
SaraDart'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:
void main() {
print("Ali's marks");
print('She said "hello"');
}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":
| Write | Means |
|---|---|
\' | a single quote |
\" | a double quote |
\n | a new line |
\t | a tab |
\\ | one backslash |
\$ | a dollar sign |
void main() {
print('Ali\'s marks');
print('Line one\nLine two');
print('Name:\tSara');
print('Folder: C:\\Users');
}Ali's marks
Line one
Line two
Name: Sara
Folder: C:\Users5. 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:
void main() {
var name = 'Zayan';
var age = 6;
var height = 3.9;
var isStudent = true;
print('$name is $age, $height ft tall, student: $isStudent');
}Zayan is 6, 3.9 ft tall, student: trueDart 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 ${...}:
void main() {
var price = 250;
var quantity = 4;
print('Total: ${price * quantity}');
print('Next year Ali will be ${20 + 1}');
}Total: 1000
Next year Ali will be 21To 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:
void main() {
var firstName = 'Sara';
var lastName = 'Khan';
var fullName = firstName + ' ' + lastName;
print(fullName);
}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:
void main() {
var message =
'Welcome to the Dart course. '
'Today we study strings.';
print(message);
}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:
void main() {
var address = '''
Ali Raza
House 12, Street 5
Lahore''';
print(address);
}Ali Raza
House 12, Street 5
LahoreA 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:
void main() {
var normal = 'Tab:\tdone';
var raw = r'Tab:\tdone';
print(normal);
print(raw);
print(r'Price: $price');
}Tab: done
Tab:\tdone
Price: $price10. Length and Indexes
Every string knows how many characters it has. Read it with .length:
void main() {
var name = 'Ali';
var password = 'dart2025';
print(name.length);
print(password.length);
print(''.length);
}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:
void main() {
var name = 'Sara';
print(name[0]);
print(name[3]);
print(name[name.length - 1]);
}S
a
aThe 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:
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()}]');
}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:
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);
}true
true
false
4
-1
false
trueindexOf 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:
void main() {
var word = 'Programming';
print(word.substring(0, 7));
print(word.substring(3));
}Program
grammingreplaceAll(from, to) swaps every match; padLeft(width, char) fills a string out to a
fixed width:
void main() {
var sentence = 'I like tea. Tea is great.';
print(sentence.replaceAll('tea', 'coffee'));
print('7'.padLeft(3, '0'));
print('-' * 10);
}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:
void main() {
var name = 'ali';
name.toUpperCase();
print(name);
name = name.toUpperCase();
print(name);
}ali
ALIThe 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:
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''');
}Registration
------------
Name: SARA KHAN
Initial: S
Email: sara@school.com
Valid: true
Letters: 9
Fee: Rs. 1500Method 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
void main() {
var city = 'Karachi';
var country = "Pakistan";
print(city);
print(country);
}Karachi
PakistanExample 2 — Escape Sequences
void main() {
print('Sara\'s book');
print('Name\tMarks');
print('Ali\t85');
print('First\nSecond');
}Sara's book
Name Marks
Ali 85
First
SecondExample 3 — Interpolation and Expressions
void main() {
var name = 'Zayan';
var apples = 3;
var oranges = 2;
print('$name has ${apples + oranges} fruits.');
}Zayan has 5 fruits.Example 4 — Concatenation
void main() {
var firstName = 'Ali';
var lastName = 'Raza';
var fullName = firstName + ' ' + lastName;
print(fullName);
print('Hello, ' + fullName + '!');
}Ali Raza
Hello, Ali Raza!Example 5 — Multi-line and Raw Strings
void main() {
var poem = '''
Roses are red,
Dart is blue.''';
var path = r'C:\new\temp';
print(poem);
print(path);
}Roses are red,
Dart is blue.
C:\new\tempHow it works
- The
'''string keeps its line break, so the poem prints on two lines. - Without the
r,\nin the path would become a line break and\ta tab. - The raw string prints every backslash exactly as written.
Example 6 — Length, Index, and Case
void main() {
var word = 'flutter';
print(word.length);
print(word[0]);
print(word.toUpperCase());
print(word.substring(0, 4));
}7
f
FLUTTER
flutExample 7 — Student Marks Card
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}');
}Student: SARA
Math: 90
Science: 84
Total: 174How it works
${student.toUpperCase()}calls a method inside the string, so it needs braces.\tputs a tab between each label and its mark.${math + science}calculates the total right inside the message.
Example 8 — Shopping Receipt
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);
}====================
Item: Notebook
Qty: 5 x Rs. 120
Total: Rs. 600
====================How it works
'=' * 20builds a divider of twenty=characters.$quantityand$priceare plain variables, so no braces are needed.${price * quantity}is a calculation, so it needs braces.
Example 9 — Bank Account Mask
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');
}Owner: Ali
Account: ******9917
Balance: Rs. 25000.5How it works
account.lengthis10, soaccount.length - 4is6.substring(6)copies from index6to the end:'9917'.- Banks show only the last four digits; the rest are hidden behind
*.
Example 10 — Temperature Report
void main() {
var city = 'islamabad';
var celsius = 30.0;
var fahrenheit = celsius * 9 / 5 + 32;
print('''
City: ${city.toUpperCase()}
Celsius: $celsius
Fahrenheit: $fahrenheit''');
}City: ISLAMABAD
Celsius: 30.0
Fahrenheit: 86.0How it works
fahrenheitis calculated first:30.0 * 9 / 5 + 32is86.0.- The multi-line string lines up the labels exactly as typed.
- Interpolation works inside
'''strings just like in normal ones.
Common Beginner Mistakes
1. An apostrophe inside single quotes
void main() {
// print('It's sunny'); // ✗
}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 +
void main() {
var age = 20;
// print('Age: ' + age); // ✗
}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
void main() {
var name = 'Ali';
print('Letters: $name.length');
print('Letters: ${name.length}');
}Letters: Ali.length
Letters: 3No 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
void main() {
// print('Cost: $5'); // ✗
print('Cost: \$5');
}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
void main() {
var name = 'ali';
name.toUpperCase(); // ✗ result thrown away
print(name);
}aliStrings are immutable. Write name = name.toUpperCase();.
6. Going past the end of a string
void main() {
var name = 'Ali';
// print(name.substring(0, 5)); // ✗ only 3 characters
}Unhandled exception:
RangeError (end): Invalid value: Not in inclusive range 0..3: 5This 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
void main() {
var name = 'Ali';
// name[0] = 'B'; // ✗
}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
$namefor a plain variable and${...}for anything else. - Use
'''for text that really spans lines, andr'...'for text full of backslashes. trim()text that comes from a user before you check or store it.- Remember that indexes start at
0and the last one islength - 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:
Username: sarak_2025
Length: 10
First letter: s
Has underscore: trueTry it yourself before opening the solution.
Show solution
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('_')}');
}Username: sarak_2025
Length: 10
First letter: s
Has underscore: trueHow it works
trim()removes the four spaces, thentoLowerCase()lowers every letter.- The trimmed name has 10 characters; the spaces are no longer counted.
username[0]is the first character, andcontains('_')returns abool.
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
- Store
'Dart'in a variable and print it, then print its length. - Print
Zayan's toytwice: once using double quotes, once using an escape sequence. - Print
Monday,Tuesday, andWednesdayon three lines using a singleprint()and\n.
Application
- Store
name = 'Ali'andmarks = 88, then printAli scored 88 marks.using interpolation. - Store
width = 6andheight = 7, then printArea: 42by calculating the area inside the string. - Store
city = 'peshawar'and print it in capital letters, then print its first and last characters. - Store
' hello dart ', trim it, and print it inside square brackets:[hello dart]. - Store
word = 'Fantastic'and printFanandtasticusingsubstring.
Challenge
- Store the sentence
'I love cats. cats are cute.'. Print it with everycatsreplaced bydogs, then print the position of the first.in the original sentence. - Store a phone number
'03001234567'. PrintPhone: 0300-*****67by combiningsubstringand*— no typing the digits by hand.
Practice Answers
Question 1 — Solution
void main() {
var language = 'Dart';
print(language);
print(language.length);
}Dart
4Question 2 — Solution
void main() {
print("Zayan's toy");
print('Zayan\'s toy');
}Zayan's toy
Zayan's toyQuestion 3 — Solution
void main() {
print('Monday\nTuesday\nWednesday');
}Monday
Tuesday
WednesdayQuestion 4 — Solution
void main() {
var name = 'Ali';
var marks = 88;
print('$name scored $marks marks.');
}Ali scored 88 marks.Question 5 — Solution
void main() {
var width = 6;
var height = 7;
print('Area: ${width * height}');
}Area: 42Question 6 — Solution
void main() {
var city = 'peshawar';
print(city.toUpperCase());
print(city[0]);
print(city[city.length - 1]);
}PESHAWAR
p
rQuestion 7 — Solution
void main() {
var text = ' hello dart ';
print('[${text.trim()}]');
}[hello dart]Question 8 — Solution
void main() {
var word = 'Fantastic';
print(word.substring(0, 3));
print(word.substring(3));
}Fan
tasticsubstring(0, 3) stops just before index 3, and substring(3) starts there.
Question 9 — Solution
void main() {
var sentence = 'I love cats. cats are cute.';
print(sentence.replaceAll('cats', 'dogs'));
print(sentence.indexOf('.'));
}I love dogs. dogs are cute.
11indexOf finds only the first match, at index 11.
Question 10 — Solution
void main() {
var phone = '03001234567';
var start = phone.substring(0, 4);
var end = phone.substring(phone.length - 2);
print('Phone: $start-${'*' * 5}$end');
}Phone: 0300-*****67start 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
- What is the difference between
'Sara'and"Sara"? - Name two ways to put an apostrophe inside a string.
- What do
\nand\tproduce? - When do you need
${}instead of just$? - Why does
'Age: ' + 20fail? - What does an
rbefore a string change? - What is the index of the first character? Of the last?
- Why does
name.toUpperCase();on its own not changename?
Key Takeaways
- A
Stringis a sequence of characters, written in single or double quotes. - A backslash starts an escape sequence:
\',\",\n,\t,\\,\$. $nameinserts 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.lengthcounts characters, and indexes run from0tolength - 1.- Methods such as
toUpperCase,trim,contains,indexOf,substring, andreplaceAllshape 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.