Creating strings
A String is a sequence of characters: names, messages, email addresses, codes. Dart accepts single or double quotes, and three quotes for text over several lines.
void main() {
String a = 'Single quotes';
String b = "Double quotes";
String c = 'It\'s easy'; // \' puts a quote inside
String d = "It's easier"; // or use the other kind of quote
String e = '''Line one
Line two''';
String path = r'C:\new\table'; // raw string: \n is not a new line
print(a);
print(b);
print(c);
print(d);
print(e);
print(path);
}
Single quotes
Double quotes
It's easy
It's easier
Line one
Line two
C:\new\table
Escape sequences: \n new line, \t tab, \' and \" quotes, \\ a backslash, \$ a dollar sign.
Joining, repeating and inserting
void main() {
String first = 'Asha', last = 'Kumari';
print(first + ' ' + last); // + joins strings
print('$first $last'); // interpolation: preferred
print('-' * 20); // * repeats
print('Name has ${first.length} letters');
}
Asha Kumari
Asha Kumari
--------------------
Name has 4 letters
Dart style prefers interpolation over +. Adjacent string literals are also joined: 'Hello ' 'world' is 'Hello world', handy for splitting long text over lines.
Length, case, trim and padding
void main() {
String s = ' Ranchi ';
print(s.length); // 10, spaces count
print(s.trim()); // remove spaces at both ends
print(s.trim().toUpperCase());
print(s.trim().toLowerCase());
print('7'.padLeft(3, '0')); // invoice numbers
print('Rice'.padRight(8, '.') + 'Rs 60');
}
10
Ranchi
RANCHI
ranchi
007
Rice....Rs 60
Strings are immutable: methods such as trim() and toUpperCase() return a new string and leave the original unchanged. To keep the result, assign it: s = s.trim();.
Searching and replacing
void main() {
String email = 'meena.k@school.in';
print(email.contains('@')); // true
print(email.startsWith('meena')); // true
print(email.endsWith('.com')); // false
print(email.indexOf('@')); // 7
print(email.replaceAll('.', '_'));
print('aaa'.replaceFirst('a', 'b'));
}
true
true
false
7
meena_k@school_in
baa
indexOf returns -1 when the text is not found.
Split and join
split cuts a string into a List<String>; join glues a list back together.
void main() {
String csv = 'Asha,Rohit,Meena';
List<String> names = csv.split(',');
print(names);
print(names.length);
print(names.join(' | '));
print('one two three'.split(' ').length);
}
[Asha, Rohit, Meena]
3
Asha | Rohit | Meena
3
Substring, characters and indexing
Characters are counted from 0. s[0] is the first character and s[s.length - 1] the last. substring(start, end) returns the piece from start up to, but not including, end.
void main() {
String s = 'Jharkhand';
print(s[0]);
print(s[s.length - 1]);
print(s.substring(0, 5));
print(s.substring(5));
print(s.split('').reversed.join());
}
J
d
Jhark
hand
dnahkrahJ
Asking for a position past the end throws a RangeError.
StringBuffer: building long text
Joining strings in a loop with + makes a new string every time. A StringBuffer collects pieces and builds the final string once:
void main() {
final sb = StringBuffer();
for (int i = 1; i <= 5; i++) {
sb.write(i);
if (i < 5) sb.write(', ');
}
sb.writeln();
sb.write('done');
print(sb.toString());
}
1, 2, 3, 4, 5
done
Comparing strings
== compares the contents of two strings (unlike Java, where == compares references). compareTo gives alphabetical order: negative, zero or positive.
void main() {
String a = 'apple', b = 'Apple';
print(a == b);
print(a.toLowerCase() == b.toLowerCase());
print('apple'.compareTo('banana'));
print('cat'.isEmpty);
print(''.isEmpty);
}
false
true
-1
false
true
Example: a word counter
void main() {
String post = ' Dart is fun and Dart is fast ';
List<String> words = post.trim().split(' ');
print('Words: ${words.length}');
print('Characters: ${post.trim().length}');
int dart = words.where((w) => w == 'Dart').length;
print('"Dart" appears $dart times');
}
Words: 7
Characters: 28
"Dart" appears 2 times
Common mistakes
- Calling
s.trim();and expectingsto change. Assign the result:s = s.trim();. - Using
substring(1, 3)and expecting three characters: the end index is not included. - Writing
'$user.name': it prints the user followed by.name. Use'${user.name}'. - Forgetting that indexes start at 0, so the last character is at
length - 1. - Writing a Windows path such as
'C:\new':\nbecomes a new line. User'C:\new'.
Key points
- Strings use single, double or triple quotes;
r'...'is a raw string. - Interpolation with
$and${ }is the preferred way to build text. - Strings are immutable; their methods return new strings.
- Key methods:
length,trim,toUpperCase,padLeft,contains,indexOf,replaceAll,split,substring. - Use
StringBufferto build text piece by piece. ==compares contents.
Practice questions
1. Write a program that prints the initials of 'asha kumari' in capitals (AK).
void main() {
String name = 'asha kumari';
String initials = name.split(' ').map((w) => w[0].toUpperCase()).join();
print(initials); // AK
}2. What does 'Hello'.substring(1, 3) return?
el: the characters at positions 1 and 2. The end position 3 is not included.
3. Write a function that checks whether a word is a palindrome, ignoring case.
bool isPalindrome(String w) {
String s = w.toLowerCase();
return s == s.split('').reversed.join();
}
void main() {
print(isPalindrome('Madam')); // true
print(isPalindrome('Dart')); // false
}4. What is printed? String s = ' hi '; s.trim(); print(s.length);
4. trim() returns a new string, but the result was not saved, so s still has its spaces.
5. Use padLeft to turn the numbers 7, 42 and 315 into the invoice codes INV-007, INV-042 and INV-315.
void main() {
for (int n in [7, 42, 315]) {
print('INV-${n.toString().padLeft(3, '0')}');
}
}