Strings and Interpolation
String Basics
Strings in Dart represent sequences of UTF-16 code units. You can create strings using single or double quotes.
dart
String single = 'Single quotes';
String double = "Double quotes";String Interpolation
String interpolation allows you to embed expressions inside strings using $ or ${}.
Simple Interpolation
dart
var name = 'Alice';
var age = 25;
print('My name is $name'); // My name is Alice
print('I am $age years old'); // I am 25 years oldExpression Interpolation
Use ${} for expressions:
dart
var price = 10;
var quantity = 3;
print('Total: \$${price * quantity}'); // Total: $30
print('Next year I will be ${age + 1}'); // Next year I will be 26Multi-line Strings
Triple Quotes
dart
String multiline = '''
This is a
multi-line
string
''';
String another = """
Another way to
create multi-line
strings
""";String Concatenation
dart
String part1 = 'Hello, ';
String part2 = 'World!';
String combined = part1 + part2; // Hello, World!
// Adjacent string literals
String message = 'This is '
'a long string '
'split across lines';Raw Strings
Raw strings treat backslashes as literal characters:
dart
String path = r'C:\Users\Documents\file.txt';
print(path); // C:\Users\Documents\file.txt
String regex = r'\d+'; // Regular expression patternEscape Sequences
dart
String newline = 'Line 1\nLine 2';
String tab = 'Column1\tColumn2';
String quote = 'She said, "Hello"';
String singleQuote = 'It\'s a nice day';
String backslash = 'Path: C:\\folder\\file';Common String Operations
Length
dart
String text = 'Hello';
print(text.length); // 5Case Conversion
dart
String name = 'Alice';
print(name.toUpperCase()); // ALICE
print(name.toLowerCase()); // aliceTrimming
dart
String padded = ' Hello ';
print(padded.trim()); // 'Hello'
print(padded.trimLeft()); // 'Hello '
print(padded.trimRight()); // ' Hello'Checking Content
dart
String text = 'Hello, World!';
print(text.contains('World')); // true
print(text.startsWith('Hello')); // true
print(text.endsWith('!')); // true
print(text.isEmpty); // false
print(text.isNotEmpty); // trueSubstring
dart
String text = 'Hello, World!';
print(text.substring(0, 5)); // Hello
print(text.substring(7)); // World!Splitting and Joining
dart
String csv = 'apple,banana,orange';
List<String> fruits = csv.split(',');
print(fruits); // [apple, banana, orange]
String joined = fruits.join(' - ');
print(joined); // apple - banana - orangeReplacing
dart
String text = 'Hello, World!';
print(text.replaceAll('o', '0')); // Hell0, W0rld!
print(text.replaceFirst('o', '0')); // Hell0, World!
print(text.replaceRange(7, 12, 'Dart')); // Hello, Dart!Index Operations
dart
String text = 'Hello';
print(text[0]); // H
print(text.indexOf('l')); // 2
print(text.lastIndexOf('l')); // 3Padding
dart
String num = '42';
print(num.padLeft(5, '0')); // 00042
print(num.padRight(5, '0')); // 42000String Comparison
dart
String str1 = 'apple';
String str2 = 'banana';
print(str1 == str2); // false
print(str1.compareTo(str2)); // negative (str1 < str2)String Buffer
For efficient string concatenation in loops:
dart
StringBuffer buffer = StringBuffer();
for (int i = 0; i < 5; i++) {
buffer.write('Number $i ');
}
String result = buffer.toString();
print(result); // Number 0 Number 1 Number 2 Number 3 Number 4Unicode and Runes
dart
String emoji = '😀';
print(emoji.length); // 2 (UTF-16 code units)
print(emoji.runes.length); // 1 (actual character)
// Iterate over characters
for (var rune in emoji.runes) {
print(String.fromCharCode(rune));
}Regular Expressions
dart
String text = 'My email is alice@example.com';
RegExp emailRegex = RegExp(r'\b[\w\.-]+@[\w\.-]+\.\w+\b');
if (emailRegex.hasMatch(text)) {
String? email = emailRegex.stringMatch(text);
print('Found email: $email'); // Found email: alice@example.com
}
// Replace with regex
String censored = text.replaceAll(emailRegex, '[EMAIL]');
print(censored); // My email is [EMAIL]Best Practices
- Use string interpolation instead of concatenation
- Use raw strings for paths and regex patterns
- Use StringBuffer for building strings in loops
- Prefer single quotes for simple strings
- Use triple quotes for multi-line strings
Complete Example
dart
void main() {
// Basic strings
String firstName = 'Alice';
String lastName = 'Johnson';
// Interpolation
String fullName = '$firstName $lastName';
print('Full name: $fullName');
// Multi-line
String address = '''
123 Main Street
New York, NY 10001
USA
''';
print('Address:$address');
// Operations
String email = 'ALICE@EXAMPLE.COM';
print('Lowercase: ${email.toLowerCase()}');
print('Contains @: ${email.contains('@')}');
// Splitting
List<String> parts = email.split('@');
print('Username: ${parts[0]}');
print('Domain: ${parts[1]}');
// Building strings
StringBuffer message = StringBuffer();
message.write('Hello, ');
message.write(firstName);
message.write('! ');
message.write('Welcome to Dart.');
print(message.toString());
}