Skip to content
AgileLogics
5 min read

Working with Strings

Prerequisites: Strings

Strings come with many useful properties and methods.

Example

void main() {
  final text = '  Hello, Dart World  ';
  final trimmed = text.trim();

  print(trimmed);
  print(trimmed.toUpperCase());
  print(trimmed.toLowerCase());
  print(trimmed.length);
  print(trimmed.startsWith('Hello'));
  print(trimmed.endsWith('!'));
  print(trimmed.contains('Dart'));
  print(trimmed.replaceAll('World', 'Friends'));
  print('a,b,c'.split(','));
  print(trimmed.indexOf('Dart'));
  print(trimmed[0]);
  print(trimmed.substring(7, 11));
  print(''.isEmpty);
  print('7'.padLeft(3, '0'));
}

Expected output

Hello, Dart World
HELLO, DART WORLD
hello, dart world
17
true
false
true
Hello, Dart Friends
[a, b, c]
7
H
Dart
true
007

Things to notice:

  • Strings are immutable: methods like toUpperCase() return a new string and leave the original unchanged.
  • Square brackets get a character by position, starting at 0.
  • substring(7, 11) takes positions 7 up to, but not including, 11.
  • padLeft(3, '0') pads to a minimum width — handy for formatting numbers like 007.

Common mistakes

  • Reading a position past the end: 'Hi'[5] throws a RangeError.
  • Using replaceAll when you meant only the first match — use replaceFirst.

Practice

Given final email = ' Ada@Example.COM ';, print it trimmed and in lowercase.

Show solution
void main() {
  final email = '  Ada@Example.COM ';
  print(email.trim().toLowerCase());
}
ada@example.com