Creating Strings
Strings in Dart are sequences of UTF-16 characters. You can use single quotes, double quotes, or triple quotes:
String s1 = 'Single quotes';
String s2 = "Double quotes";
String s3 = 'It\'s a beautiful day'; // escaped apostrophe
String s4 = "She said \"hello\""; // escaped quotes
String Interpolation
Embed variables and expressions directly into strings using $variable or $${expression}:
String name = 'Dart';
int version = 3;
print('Welcome to $name!');
print('$name version $${version + 0} is great!');
print('2 + 2 = $${2 + 2}'); // 2 + 2 = 4
Multi-line Strings
Use triple quotes (''' or """) for strings that span multiple lines:
String poem = '''
Roses are red,
Violets are blue,
Dart is awesome,
And so are you!
''';
print(poem);
String Properties
String text = 'Hello, Dart!';
print(text.length); // 12
print(text.isEmpty); // false
print(text.isNotEmpty); // true
Common String Methods
| Method | Description | Example |
toUpperCase() | All uppercase | 'hello'.toUpperCase() → 'HELLO' |
toLowerCase() | All lowercase | 'HELLO'.toLowerCase() → 'hello' |
trim() | Remove leading/trailing whitespace | ' hi '.trim() → 'hi' |
contains() | Check if string contains substring | 'hello'.contains('ell') → true |
startsWith() | Check prefix | 'dart'.startsWith('d') → true |
endsWith() | Check suffix | 'dart'.endsWith('t') → true |
replaceAll() | Replace all occurrences | 'aa'.replaceAll('a','b') → 'bb' |
split() | Split into a List | 'a,b,c'.split(',') → ['a','b','c'] |
substring() | Extract part of string | 'Hello'.substring(1,3) → 'el' |
Escape Characters
| Escape | Meaning |
\n | Newline |
\t | Tab |
\\ | Backslash |
\' | Single quote |
\" | Double quote |
\$ | Dollar sign (avoid interpolation) |
Full Example
void main() {
String fullName = 'John Doe';
String email = ' john@example.com ';
print(fullName.toUpperCase()); // JOHN DOE
print(email.trim()); // john@example.com
print(fullName.contains('John')); // true
print(fullName.replaceAll('o', '0')); // J0hn D0e
print(fullName.split(' ')); // [John, Doe]
List<String> parts = fullName.split(' ');
print('First: $${parts[0]}, Last: $${parts[1]}');
}
Output:
JOHN DOE
john@example.com
true
J0hn D0e
[John, Doe]
First: John, Last: Doe
💪 Exercise
- Create a string with your full name. Print it in uppercase and lowercase.
- Check if your name contains the letter 'a'.
- Split a comma-separated list of hobbies:
'reading,coding,gaming' and print each hobby.
🧠 Quiz
1. How do you embed a variable in a Dart string?
- A) {variable}
- B) $variable ✅
- C) #variable
- D) @variable
2. Which method splits a string into a list?
- A) divide()
- B) cut()
- C) split() ✅
- D) separate()
Summary
Dart strings are created with single, double, or triple quotes. String interpolation ($var / $${expr}) embeds values. Key methods include toUpperCase(), trim(), contains(), split(), and substring(). Use escape characters for special characters within strings.