Strings and Interpolation

String Basics

Strings in Dart represent sequences of UTF-16 code units. You can create strings using single or double quotes.

String single = 'Single quotes';
String double = "Double quotes";

String Interpolation

String interpolation allows you to embed expressions inside strings using $ or ${}.

Simple Interpolation

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 old

Expression Interpolation

Use ${} for expressions:

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 26

Multi-line Strings

Triple Quotes

String multiline = '''
This is a
multi-line
string
''';

String another = """
Another way to
create multi-line
strings
""";

String Concatenation

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:

String path = r'C:\Users\Documents\file.txt';
print(path);  // C:\Users\Documents\file.txt

String regex = r'\d+';  // Regular expression pattern

Escape Sequences

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

String text = 'Hello';
print(text.length);  // 5

Case Conversion

String name = 'Alice';
print(name.toUpperCase());  // ALICE
print(name.toLowerCase());  // alice

Trimming

String padded = '  Hello  ';
print(padded.trim());       // 'Hello'
print(padded.trimLeft());   // 'Hello  '
print(padded.trimRight());  // '  Hello'

Checking Content

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);            // true

Substring

String text = 'Hello, World!';

print(text.substring(0, 5));    // Hello
print(text.substring(7));       // World!

Splitting and Joining

String csv = 'apple,banana,orange';
List<String> fruits = csv.split(',');
print(fruits);  // [apple, banana, orange]

String joined = fruits.join(' - ');
print(joined);  // apple - banana - orange

Replacing

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

String text = 'Hello';

print(text[0]);              // H
print(text.indexOf('l'));    // 2
print(text.lastIndexOf('l')); // 3

Padding

String num = '42';

print(num.padLeft(5, '0'));   // 00042
print(num.padRight(5, '0'));  // 42000

String Comparison

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:

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 4

Unicode and Runes

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

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

  1. Use string interpolation instead of concatenation
  2. Use raw strings for paths and regex patterns
  3. Use StringBuffer for building strings in loops
  4. Prefer single quotes for simple strings
  5. Use triple quotes for multi-line strings

Complete Example

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());
}

Next Steps