Strings
## Learning Objectives
- Master string creation and manipulation
- Understand string interpolation
- Work with Unicode and runes
- Use string methods effectively
## Creating Strings
### Basic Strings
```dart
void main() {
// Single quotes
var single = 'Hello World';
// Double quotes
var double = "Hello World";
// Triple quotes for multi-line
var multi = '''
This is a
multi-line
string
''';
// Raw string (escape handling disabled)
var raw = r'C:\Users\NewFolder';
print(raw); // C:\Users\NewFolder
}
```
### String Immutability
```dart
void main() {
var s1 = 'Hello';
var s2 = s1; // Both reference same object
s1 = 'World'; // Creates new string
print(s1); // World
print(s2); // Hello (unchanged)
}
```
## String Interpolation
### Basic Interpolation
```dart
void main() {
var name = 'Alice';
var age = 30;
print('Name: $name'); // Name: Alice
print('Age: $age'); // Age: 30
print('$name is $age'); // Alice is 30
}
```
### Expression Interpolation
```dart
void main() {
var a = 5;
var b = 3;
print('$a + $b = ${a + b}'); // 5 + 3 = 8
print('${a > b ? "greater" : "less"}'); // greater
}
```
### Avoiding Dollar Signs
```dart
void main() {
// Use \ to escape
print('\$100'); // $100
// Use raw string
var price = r'$100';
print(price); // $100
}
```
## String Methods
### Length and Check
```dart
void main() {
var s = 'Hello World';
print(s.length); // 11
print(s.isEmpty); // false
print(s.isNotEmpty); // true
print(s.contains('World')); // true
print(s.startsWith('Hello')); // true
print(s.endsWith('!')); // false
}
```
### Case Operations
```dart
void main() {
var s = 'Hello World';
print(s.toUpperCase()); // HELLO WORLD
print(s.toLowerCase()); // hello world
}
```
### Searching
```dart
void main() {
var s = 'Hello World';
print(s.indexOf('World')); // 6
print(s.lastIndexOf('o')); // 7
print(s.contains('foo')); // false
}
```
### Substrings
```dart
void main() {
var s = 'Hello World';
print(s.substring(6)); // World
print(s.substring(0, 5)); // Hello
print(s.split(' ')); // [Hello, World]
}
```
### Trimming
```dart
void main() {
var s = ' Hello ';
print(s.trim()); // Hello
print(s.trimLeft()); // Hello__
print(s.trimRight()); // __Hello
}
```
### Replacing
```dart
void main() {
var s = 'Hello World';
print(s.replaceAll('World', 'Dart')); // Hello Dart
print(s.replaceFirst('l', 'L')); // HeLlo World
print(s.replaceRange(0, 5, 'Hi')); // Hi World
}
```
### Splitting
```dart
void main() {
var csv = 'apple,banana,orange';
print(csv.split(',')); // [apple, banana, orange]
var words = 'Hello World';
print(words.split(' ')); // [Hello, World]
// With limit
print(csv.split(',', 2)); // [apple, banana,orange]
}
```
### Padding
```dart
void main() {
var s = '42';
print(s.padLeft(5, '0')); // 00042
print(s.padRight(5, '.')); // 42...
}
```
## StringBuffer
### Efficient String Building
```dart
void main() {
var buffer = StringBuffer();
buffer.write('Hello');
buffer.write(' ');
buffer.write('World');
print(buffer.toString()); // Hello World
// Direct initialization
var sb = StringBuffer('Initial');
sb.write(' More');
print(sb.toString()); // Initial More
}
```
### With Collection
```dart
void main() {
var items = ['apple', 'banana', 'orange'];
var buffer = StringBuffer('Fruits:');
for (var item in items) {
buffer.write(' $item');
}
print(buffer.toString()); // Fruits: apple banana orange
}
```
## Runes and Unicode
### Unicode Basics
```dart
void main() {
// Unicode code points
var euro = '\u20AC'; // β¬
var heart = '\u2665'; // β₯
var smiley = '\u{1F600}'; // π (extended)
print('Euro: $euro');
print('Heart: $heart');
print('Smiley: $smiley');
}
```
### Runes Property
```dart
void main() {
var emoji = 'Hello π';
print(emoji.runes.toList()); // [72, 101, 108, 108, 111, 32, 128075]
// Iterate over runes
for (var code in emoji.runes) {
print('Code: $code, Char: ${String.fromCharCode(code)}');
}
}
```
### Grapheme Clusters
```dart
void main() {
var flag = 'πΊπΈ';
print(flag.runes.toList()); // [127482, 127480]
print(flag.length); // 2 (code units)
print(flag.runes.length); // 2 (runes)
// For user-perceived characters, use characters package
}
```
## Pattern Matching
### Regular Expressions
```dart
void main() {
var email = RegExp(r'^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$');
print(email.hasMatch('test@email.com')); // true
print(email.hasMatch('invalid')); // false
}
```
### Replace with Pattern
```dart
void main() {
var text = 'Hello World World World';
// Replace all
print(text.replaceAll(RegExp(r'World'), 'Dart'));
// Hello Dart Dart Dart
// Replace first
print(text.replaceFirst(RegExp(r'World'), 'Dart'));
// Hello Dart World World
}
```
### Extract Matches
```dart
void main() {
var text = 'Price: 19.99';
var match = RegExp(r'(\d+\.\d+)').firstMatch(text);
if (match != null) {
print(match.group(0)); // 19.99
print(match.start); // 7
print(match.end); // 12
}
}
```
## String Comparison
```dart
void main() {
var a = 'hello';
var b = 'hello';
var c = 'world';
print(a == b); // true
print(a == c); // false
print(a.compareTo(b)); // 0 (equal)
print(a.compareTo(c)); // negative (a < c)
}
```
## String Verification Methods
```dart
void main() {
var num = '123';
var text = 'abc';
print(num.contains(RegExp(r'^\d+$'))); // true
print(text.contains(RegExp(r'^\d+$'))); // false
// isAlpha, isNumeric etc. not built-in
// Use RegExp or parse methods
}
```
## Summary
- Strings: `''`, `""`, `''' '''`, `r''` (raw)
- Interpolation: `$var`, `${expr}`
- Immutable: operations return new strings
- Methods: length, indexOf, substring, split, replaceAll, trim
- StringBuffer for efficient concatenation
- Runes for Unicode: `string.runes`
- RegExp for pattern matching
Comments
Comments powered by Giscus
To enable comments, add your Giscus embed code here.
Learn more about Giscus β